下面列出了怎么用com.bumptech.glide.DrawableRequestBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
private DrawableRequestBuilder<Uri> renderScreenSize(Uri uri)
{
DrawableRequestBuilder<Uri> request =
mGlideManager.loadScreen(uri, generateSignature(mData), mSuggestedSize);
// If we have a non-null placeholder, use that and do NOT ever render a
// tiny thumbnail to prevent un-intended "flash of low resolution image"
if (mSessionPlaceholderBitmap.isPresent())
{
Log.v(TAG, "using session bitmap as placeholder");
return request.placeholder(new BitmapDrawable(mContext.getResources(),
mSessionPlaceholderBitmap.get()));
}
// If we do not have a placeholder bitmap, render a thumbnail with
// the default placeholder resource like normal.
return request
.thumbnail(renderTinySize(uri));
}
@Override
public void loadImageWithThumbnail(Context context, XImageView imageView) {
String url = imageView.getThumbnailOption().getUrl();
if (url == null) {
Glide.with(context)
.load(imageView.getUrl())
.thumbnail(XImageConfig.SIZE_MULTIPLIER)
.into(imageView.getImageView());
} else {
DrawableRequestBuilder<String> thumbnailRequest = Glide
.with(context)
.load(url);
Glide.with(context)
.load(imageView.getUrl())
.thumbnail(thumbnailRequest)
.into(imageView.getImageView());
}
}
private DrawableRequestBuilder load(Object object, RequestManager with){
DrawableRequestBuilder builder = null;
if(object instanceof String){
String imageUrl = (String) object;
if(!imageUrl.startsWith("http://")){
imageUrl = Api.IMG_SERVER_URL.concat(imageUrl);
}
builder = with.load(imageUrl);
}else if(object instanceof Integer){
builder = with.load((Integer) object);
}else if(object instanceof File){
builder = with.load((File) object);
}else if(object instanceof Uri){
builder = with.load((Uri) object);
}else if(object instanceof Byte[]){
builder = with.load((Byte[]) object);
}
return builder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
GankBean gankBean = mData.get(position);
holder.tvHomeGankTitle.setText(gankBean.desc);
holder.tvHomeGankAuthor.setText(gankBean.who);
holder.tvHomeGankDate.setText(DateUtils.formatDateDetailDay(DateUtils.parseStringToDate(gankBean.publishedAt)));
if (gankBean.images != null && !gankBean.images.isEmpty()) {
holder.ivHomeGankImg.setVisibility(View.VISIBLE);
DrawableRequestBuilder<String> requestBuilder = Glide.with(mContext)
.load(gankBean.images.get(0)+"?imageView2/0/w/400")
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.error(R.color.accent)
.crossFade();
requestBuilder.into(holder.ivHomeGankImg);
}else {
holder.ivHomeGankImg.setVisibility(View.GONE);
}
}
public static void loadImage(Context context, ImageView view,
@NonNull String url, @Nullable String thumbUrl,
@Size(2) @Px int[] size, @Nullable @Size(2) @Px int[] thumbSize,
@Nullable BitmapTransformation[] ts, @Nullable OnLoadImageListener l) {
if (thumbSize == null) {
thumbSize = new int[] {Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL};
}
DrawableRequestBuilder<String> thumb = TextUtils.isEmpty(thumbUrl) ? null : Glide.with(getValidContext(context))
.load(ensureUrl(thumbUrl))
.override(thumbSize[0], thumbSize[1])
.diskCacheStrategy(
thumbSize[0] == Target.SIZE_ORIGINAL
? DiskCacheStrategy.NONE
: DiskCacheStrategy.SOURCE
).listener(
new BaseRequestListener<>(() -> view.setTag(R.id.tag_item_image_fade_in_flag, false))
);
loadImage(context, view, url, thumb, size, ts, l);
}
public void load(final DrawableRequestBuilder request) {
if (getWidth() > 0 && getHeight() > 0) {
request.dontAnimate().into(new SimpleTarget<GlideDrawable>(getWidth(), getHeight()) {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
transition(resource);
}
});
} else {
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
load(request);
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
final Post post = posts.get(position);
holder.title.setText(post.getTitle());
DrawableRequestBuilder<String> request = Glide.with(context)
.load(post.getImage_url());
if (post.getImage_url().endsWith(".gif")) {
request.diskCacheStrategy(DiskCacheStrategy.SOURCE).into(holder.artwork);
} else {
request.into(holder.artwork);
}
holder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(post.getUrl()));
context.startActivity(i);
}
});
}
/**
*
* @param uri
* @param defDrawable
* @param mTransformation 自定义Bitmap
*/
public void load(String uri, int defDrawable, BitmapTransformation mTransformation){
DrawableRequestBuilder<String> builder=Glide.with(getContext()).load(uri).placeholder(defDrawable);
//监听
if(mListener!=null){
builder.listener(mListener);
}
//特殊图像
if(mTransformation!=null){
builder.transform(mTransformation).into(this);
}else{
builder.into(this);
}
}
/**
* Create a full size drawable request for a given width and height that is
* as large as we can reasonably load into a view without causing massive
* jank problems or blank frames due to overly large textures.
*/
public final DrawableRequestBuilder<Uri> loadFull(Uri uri, Key key, Size original)
{
Size size = clampSize(original, MAXIMUM_FULL_RES_PIXELS, getMaxImageDisplaySize());
return mLargeImageBuilder
.clone()
.load(uri)
.signature(key)
.override(size.width(), size.height());
}
/**
* Create a full size drawable request for a given width and height that is
* smaller than loadFull, but is intended be large enough to fill the screen
* pixels.
*/
public DrawableRequestBuilder<Uri> loadScreen(Uri uri, Key key, Size original)
{
Size size = clampSize(original, MAXIMUM_SMOOTH_PIXELS, getMaxImageDisplaySize());
return mLargeImageBuilder
.clone()
.load(uri)
.signature(key)
.override(size.width(), size.height());
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, song, ignoreMediaStore)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.signature(createSignature(song));
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, artist, noCustomImage)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.priority(Priority.LOW)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.signature(createSignature(artist));
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, song, ignoreMediaStore)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.signature(createSignature(song));
}
/**
* Uses Glide to load image into an ImageView
*
* @param weakRef the {@link WeakReference} of a given subclass of {@link Context}
* @param params the {@link GlideTaskParams}
*/
public static <CTX extends Context, T extends ImageView> void loadImage(@NonNull WeakReference<CTX> weakRef,
@NonNull GlideTaskParams<T> params) {
if (!AbstractWeakReferenceUtils.isAlive(weakRef)) {
return;
}
DrawableRequestBuilder<String> requestBuilder = Glide.with(weakRef.get()).load(params.getPath())
.diskCacheStrategy(DiskCacheStrategy.ALL);
load(applyDimens(requestBuilder, params), params);
}
private void loadImageView(Object object, int placeholderId, int errorId, Transformation transform, ImageView imageView){
DrawableRequestBuilder builder = load(object, with());
if(builder != null){
// 设置占位图
if(placeholderId != -1) builder.placeholder(placeholderId);
// 设置加载错误时占位图
if(errorId != -1) builder.error(errorId);
// 设置 transform
if(transform != null) builder.bitmapTransform(transform);
// 加载到图片
builder.into(imageView);
}
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, song, ignoreMediaStore)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.signature(createSignature(song));
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, artist, noCustomImage, forceDownload)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.priority(Priority.LOW)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.signature(createSignature(artist));
}
/**
* 下载图片转换圆角
* @param context
* @param imageRes
* @param view
* @param radius 圆角度
*/
public static void loadAdapterRadius(Context context, String imageRes, ImageView view,int radius){
DrawableRequestBuilder requestBuilder = Glide.with(context)
.load(imageRes)
.centerCrop()
.crossFade()
.transform(new GlideRoundTransform(context, radius))
.diskCacheStrategy(DiskCacheStrategy.ALL);
requestBuilder.into(view);
}
/**
* 下载图片转换圆角
* @param context
* @param imageRes
* @param view
* @param radius
*/
public static void loadAdapterRadius(Context context, @DrawableRes int imageRes, ImageView view, int radius){
DrawableRequestBuilder requestBuilder = Glide.with(context)
.load(imageRes)
.centerCrop()
.crossFade()
.transform(new GlideRoundTransform(context, radius))
.diskCacheStrategy(DiskCacheStrategy.ALL);
requestBuilder.into(view);
}
public static void loadImage(Context context, ImageView view,
@NonNull String url, @DrawableRes int thumbResId, @Size(2) @Px int[] size,
@Nullable BitmapTransformation[] ts, @Nullable OnLoadImageListener l) {
DrawableRequestBuilder<Integer> thumb = thumbResId == 0 ? null : Glide.with(getValidContext(context))
.load(thumbResId)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.listener(new BaseRequestListener<>(() -> view.setTag(R.id.tag_item_image_fade_in_flag, false)));
loadImage(context, view, url, thumb, size, ts, l);
}
private static void loadImage(Context context, ImageView view,
@NonNull String url, @Nullable DrawableRequestBuilder thumbnailRequest,
@Size(2) @Px int[] size,
@Nullable BitmapTransformation[] ts, @Nullable OnLoadImageListener l) {
view.setTag(R.id.tag_item_image_fade_in_flag, true);
if (ts == null) {
ts = new BitmapTransformation[] {new NullTransformation(context)};
}
Glide.with(getValidContext(context))
.load(ensureUrl(url))
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(size[0], size[1])
.thumbnail(thumbnailRequest)
.animate(v -> {
Boolean fadeInFlag = (Boolean) v.getTag(R.id.tag_item_image_fade_in_flag);
if (fadeInFlag == null || fadeInFlag) {
v.setTag(R.id.tag_item_image_fade_in_flag, false);
ObjectAnimator animator = ObjectAnimator.ofFloat(v, "alpha", 0f, 1f);
animator.setDuration(300);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.start();
}
}).transform(ts)
.listener(new BaseRequestListener<>(l))
.into(view);
}
private void bindLibrary(final LibraryHolder holder, final Library lib) {
holder.name.setText(lib.name);
holder.description.setText(lib.description);
DrawableRequestBuilder<String> request = Glide.with(holder.image.getContext())
.load(lib.imageUrl)
.placeholder(R.drawable.avatar_placeholder);
if (lib.circleCrop) {
request.transform(circleCrop);
}
request.into(holder.image);
}
public static DrawableRequestBuilder<String> urlNoPlaceHolder(Context context, String url) {
return Glide.with(context)
.fromString()
.load(url)
// .placeholder(R.drawable.placeholder);
// .error(R.drawable.error)
// .animate(R.anim.my_fancy_anim)
;
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, song, ignoreMediaStore)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.signature(createSignature(song));
}
public DrawableRequestBuilder<GlideDrawable> build() {
//noinspection unchecked
return createBaseRequest(requestManager, artist, noCustomImage)
.diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
.error(DEFAULT_ERROR_IMAGE)
.animate(DEFAULT_ANIMATION)
.priority(Priority.LOW)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.signature(createSignature(artist));
}
private GenericRequestBuilder buildThumbnailGlideRequest(@NonNull Slide slide, @NonNull MasterSecret masterSecret) {
@SuppressWarnings("ConstantConditions")
DrawableRequestBuilder<DecryptableUri> builder = Glide.with(getContext()).load(new DecryptableUri(masterSecret, slide.getThumbnailUri()))
.crossFade()
.transform(new RoundedCorners(getContext(), true, radius, backgroundColorHint));
if (slide.isInProgress()) return builder;
else return builder.error(R.drawable.ic_missing_thumbnail_picture);
}
private void loadImageThumbnailRequest() {
DrawableRequestBuilder<String> thumbnailRequest = Glide
.with(context)
.load(eatFoodyImages[2])
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE);
Glide
.with(context)
.load(UsageExampleGifAndVideos.gifUrl)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.thumbnail(thumbnailRequest)
.into(imageView3);
}
private DrawableRequestBuilder<Uri> renderFullSize(Uri uri)
{
Size size = mData.getDimensions();
return mGlideManager.loadFull(uri, generateSignature(mData), size)
.thumbnail(renderScreenSize(uri));
}
private DrawableRequestBuilder getCommGlide() {
return Glide.with(mContext)
.load(Url.IMAGE_URL_PERU)
.error(R.drawable.error)
.placeholder(R.drawable.placeholder);
}
public void setSource(ReadableMap params) {
mParams = params;
@Nullable Uri mUri = null;
String source = params.hasKey("uri") ? params.getString("uri") : null;
String thumbnail = params.hasKey("thumbnail") ? params.getString("thumbnail") : null;
ReadableMap headers = params.hasKey("headers") ? params.getMap("headers") : null;
//handle base64
if (source.startsWith("data:image/png;base64,")){
Glide
.with(this.getContext())
.load(Base64.decode(source.replaceAll("data:image\\/.*;base64,", ""), Base64.DEFAULT))
.into(this)
;
return;
}
boolean useStorageFile = false ;
// handle bundled app resources
try {
mUri = Uri.parse(source);
// Verify scheme is set, so that relative uri (used by static resources) are not handled.
if (mUri.getScheme() == null) {
mUri = null;
} else if(
!mUri.getScheme().equals("http") &&
!mUri.getScheme().equals("https")
){
useStorageFile = true ;
if (!mInitialized) {
this.setImageURI(mUri);
}
}
} catch (Exception e) {
// ignore malformed uri, then attempt to extract resource ID.
}
if (mUri == null) {
mUri = mResourceDrawableIdHelper.getResourceDrawableUri(
this.getContext(),
source
);
Glide
.with(this.getContext())
.load(mUri)
.into(this);
} else if (useStorageFile) {
Glide
.with(this.getContext())
.load(mUri)
.into(this);
} else {
// Handle an http / https address
RequestListener listener = this.getRequestListener();
LazyHeaders.Builder lazyHeaders = new LazyHeaders.Builder();
Log.d("null headers", String.valueOf(headers != null));
if(headers != null){
ReadableMapKeySetIterator it = headers.keySetIterator();
Log.d("next headers", String.valueOf(it.hasNextKey()));
while(it.hasNextKey()){
String Key = it.nextKey();
lazyHeaders.addHeader(Key, headers.getString(Key));
}
}
Log.d("thing", mUri.toString());
DrawableRequestBuilder builder = Glide
.with(this.getContext())
.load(new GlideUrl(mUri.toString(), lazyHeaders.build()))
.listener(listener);
//set thumbnails
if(thumbnail != null) {
DrawableRequestBuilder<String> thumbnailRequest = Glide
.with(this.getContext())
.load(thumbnail);
builder = builder.thumbnail(thumbnailRequest);
}
builder.into(this);
}
this.setChangeListeners();
}