下面列出了怎么用com.bumptech.glide.load.resource.gif.GifDrawable的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
AttachmentSecret attachmentSecret = AttachmentSecretProvider.getInstance(context).getOrCreateAttachmentSecret();
byte[] secret = attachmentSecret.getModernKey();
registry.prepend(File.class, File.class, UnitModelLoader.Factory.getInstance());
registry.prepend(InputStream.class, new EncryptedCacheEncoder(secret, glide.getArrayPool()));
registry.prepend(File.class, Bitmap.class, new EncryptedBitmapCacheDecoder(secret, new StreamBitmapDecoder(new Downsampler(registry.getImageHeaderParsers(), context.getResources().getDisplayMetrics(), glide.getBitmapPool(), glide.getArrayPool()), glide.getArrayPool())));
registry.prepend(File.class, GifDrawable.class, new EncryptedGifCacheDecoder(secret, new StreamGifDecoder(registry.getImageHeaderParsers(), new ByteBufferGifDecoder(context, registry.getImageHeaderParsers(), glide.getBitmapPool(), glide.getArrayPool()), glide.getArrayPool())));
registry.prepend(BlurHash.class, Bitmap.class, new BlurHashResourceDecoder());
registry.prepend(Bitmap.class, new EncryptedBitmapResourceEncoder(secret));
registry.prepend(GifDrawable.class, new EncryptedGifDrawableResourceEncoder(secret));
registry.append(ContactPhoto.class, InputStream.class, new ContactPhotoLoader.Factory(context));
registry.append(DecryptableUri.class, InputStream.class, new DecryptableStreamUriLoader.Factory(context));
registry.append(AttachmentModel.class, InputStream.class, new AttachmentStreamUriLoader.Factory());
registry.append(ChunkedImageUrl.class, InputStream.class, new ChunkedImageUrlLoader.Factory());
registry.append(StickerRemoteUri.class, InputStream.class, new StickerRemoteUriLoader.Factory());
registry.append(BlurHash.class, BlurHash.class, new BlurHashModelLoader.Factory());
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}
private GifBitmapWrapper decodeGifWrapper(InputStream bis, int width, int height) throws IOException {
GifBitmapWrapper result = null;
Resource<GifDrawable> gifResource = gifDecoder.decode(bis, width, height);
if (gifResource != null) {
GifDrawable drawable = gifResource.get();
// We can more efficiently hold Bitmaps in memory, so for static GIFs, try to return Bitmaps
// instead. Returning a Bitmap incurs the cost of allocating the GifDrawable as well as the normal
// Bitmap allocation, but since we can encode the Bitmap out as a JPEG, future decodes will be
// efficient.
if (drawable.getFrameCount() > 1) {
result = new GifBitmapWrapper(null /*bitmapResource*/, gifResource);
} else {
Resource<Bitmap> bitmapResource = new BitmapResource(drawable.getFirstFrame(), bitmapPool);
result = new GifBitmapWrapper(bitmapResource, null /*gifResource*/);
}
}
return result;
}
@Override
public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
int w = DensityUtil.getScreenWidth(mContext);
int hh = resource.getIntrinsicHeight();
int ww = resource.getIntrinsicWidth();
int high = hh * (w - 50) / ww;
Rect rect = new Rect(20, 20, w - 30, high);
resource.setBounds(rect);
urlDrawable.setBounds(rect);
urlDrawable.setDrawable(resource);
gifDrawables.add(resource);
resource.setCallback(mTextView);
resource.start();
resource.setLoopCount(GifDrawable.LOOP_FOREVER);
mTextView.setText(mTextView.getText());
mTextView.invalidate();
}
@Override
public void onResourceReady(Drawable resource, @Nullable Transition<? super Drawable> transition) {
super.onResourceReady(resource, transition);
BadgedFourThreeImageView badgedImageView = (BadgedFourThreeImageView) getView();
if (resource instanceof GifDrawable) {
Bitmap image = ((GifDrawable) resource).getFirstFrame();
if (image != null) {
// look at the corner to determine the gif badge color
int cornerSize = (int) (56 * getView().getContext().getResources().getDisplayMetrics
().scaledDensity);
Bitmap corner = Bitmap.createBitmap(image,
image.getWidth() - cornerSize,
image.getHeight() - cornerSize,
cornerSize, cornerSize);
boolean isDark = ColorUtils.isDark(corner);
corner.recycle();
badgedImageView.setBadgeColor(ContextCompat.getColor(getView().getContext(),
isDark ? R.color.gif_badge_dark_image : R.color.gif_badge_light_image));
} else {
badgedImageView.setBadgeColor(ContextCompat.getColor(getView().getContext(),
R.color.gif_badge_light_image));
}
}
}
@Override public boolean onResourceReady(TranscodeType resource, Object model, Target<TranscodeType> target, DataSource dataSource, boolean isFirstResource) {
boolean callbackResult = this.callback != null && this.callback.onResourceReady(resource, model, target, dataSource, isFirstResource);
Bitmap b = null;
if (resource instanceof BitmapDrawable) {
b = ((BitmapDrawable) resource).getBitmap();
} else if (resource instanceof GifDrawable) {
b = ((GifDrawable) resource).getFirstFrame();
} else if (target instanceof BitmapHolder) {
b = ((BitmapHolder) target).getBitmap();
}
if (b != null) {
start(b);
}
return callbackResult;
}
@Nullable
@Override
public Resource<GifDrawable> decode(@NonNull File source, int width, int height, @NonNull Options options) throws IOException {
Log.i(TAG, "Encrypted GIF cache decoder running...");
try (InputStream inputStream = createEncryptedInputStream(secret, source)) {
return gifDecoder.decode(inputStream, width, height, options);
}
}
@Override
public boolean encode(@NonNull Resource<GifDrawable> data, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = data.get();
try (OutputStream outputStream = createEncryptedOutputStream(secret, file)) {
ByteBufferUtil.toStream(drawable.getBuffer(), outputStream);
return true;
} catch (IOException e) {
Log.w(TAG, e);
return false;
}
}
public byte[] getData(boolean forMms) throws ExecutionException, InterruptedException {
synchronized (this) {
while (!modelReady) {
Util.wait(this, 0);
}
}
GifDrawable drawable = glideRequests.asGif()
.load(forMms ? new ChunkedImageUrl(image.getGifMmsUrl(), image.getMmsGifSize()) :
new ChunkedImageUrl(image.getGifUrl(), image.getGifSize()))
.submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
return ByteBufferUtil.toBytes(drawable.getBuffer());
}
public ImageVideoGifDrawableLoadProvider(DataLoadProvider<ImageVideoWrapper, Bitmap> bitmapProvider,
DataLoadProvider<InputStream, GifDrawable> gifProvider, BitmapPool bitmapPool) {
final GifBitmapWrapperResourceDecoder decoder = new GifBitmapWrapperResourceDecoder(
bitmapProvider.getSourceDecoder(),
gifProvider.getSourceDecoder(),
bitmapPool
);
cacheDecoder = new FileToStreamDecoder<GifBitmapWrapper>(new GifBitmapWrapperStreamResourceDecoder(decoder));
sourceDecoder = decoder;
encoder = new GifBitmapWrapperResourceEncoder(bitmapProvider.getEncoder(), gifProvider.getEncoder());
//TODO: what about the gif provider?
sourceEncoder = bitmapProvider.getSourceEncoder();
}
GifBitmapWrapperResourceDecoder(ResourceDecoder<ImageVideoWrapper, Bitmap> bitmapDecoder,
ResourceDecoder<InputStream, GifDrawable> gifDecoder, BitmapPool bitmapPool, ImageTypeParser parser,
BufferedStreamFactory streamFactory) {
this.bitmapDecoder = bitmapDecoder;
this.gifDecoder = gifDecoder;
this.bitmapPool = bitmapPool;
this.parser = parser;
this.streamFactory = streamFactory;
}
public GifBitmapWrapper(Resource<Bitmap> bitmapResource, Resource<GifDrawable> gifResource) {
if (bitmapResource != null && gifResource != null) {
throw new IllegalArgumentException("Can only contain either a bitmap resource or a gif resource, not both");
}
if (bitmapResource == null && gifResource == null) {
throw new IllegalArgumentException("Must contain either a bitmap resource or a gif resource");
}
this.bitmapResource = bitmapResource;
this.gifResource = gifResource;
}
@Override
public void recycle() {
Resource<Bitmap> bitmapResource = data.getBitmapResource();
if (bitmapResource != null) {
bitmapResource.recycle();
}
Resource<GifDrawable> gifDataResource = data.getGifResource();
if (gifDataResource != null) {
gifDataResource.recycle();
}
}
private static <A, R> FixedLoadProvider<A, InputStream, GifDrawable, R> buildProvider(Glide glide,
ModelLoader<A, InputStream> streamModelLoader, Class<R> transcodeClass,
ResourceTranscoder<GifDrawable, R> transcoder) {
if (streamModelLoader == null) {
return null;
}
if (transcoder == null) {
transcoder = glide.buildTranscoder(GifDrawable.class, transcodeClass);
}
DataLoadProvider<InputStream, GifDrawable> dataLoadProvider = glide.buildDataProvider(InputStream.class,
GifDrawable.class);
return new FixedLoadProvider<A, InputStream, GifDrawable, R>(streamModelLoader, transcoder, dataLoadProvider);
}
GifTypeRequest(GenericRequestBuilder<ModelType, ?, ?, ?> other,
ModelLoader<ModelType, InputStream> streamModelLoader, RequestManager.OptionsApplier optionsApplier) {
super(buildProvider(other.glide, streamModelLoader, GifDrawable.class, null), GifDrawable.class, other);
this.streamModelLoader = streamModelLoader;
this.optionsApplier = optionsApplier;
// Default to animating.
crossFade();
}
/**
* {@inheritDoc}
*/
@Deprecated
@Override
public GifRequestBuilder<ModelType> crossFade(Animation animation, int duration) {
super.animate(new DrawableCrossFadeFactory<GifDrawable>(animation, duration));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GifRequestBuilder<ModelType> crossFade(int animationId, int duration) {
super.animate(new DrawableCrossFadeFactory<GifDrawable>(context, animationId,
duration));
return this;
}
/**
* {@inheritDoc}
*/
@Override
public GifRequestBuilder<ModelType> listener(
RequestListener<? super ModelType, GifDrawable> requestListener) {
super.listener(requestListener);
return this;
}
public SaveGIFToFileAsyncTask(GifDrawable resource, String cacheDirPath, String fileName,
SaveGIFToFileAsyncTaskListener saveImageToFileAsyncTaskListener) {
this.resource = resource;
this.cacheDirPath = cacheDirPath;
this.fileName = fileName;
this.saveImageToFileAsyncTaskListener = saveImageToFileAsyncTaskListener;
}
/**
* 图片显示
* @param uri Image Uri
* @param imageView ImageView
* @param options {@link RequestOptions}
* @param listener 加载监听事件
*/
public void displayImageToGif(final String uri, final ImageView imageView, final RequestOptions options,
final RequestListener<GifDrawable> listener) {
if (mRequestManager != null && imageView != null) {
if (options != null) {
mRequestManager.asGif().load(uri).apply(options).listener(listener).into(imageView);
} else {
mRequestManager.asGif().load(uri).listener(listener).into(imageView);
}
}
}
/**
* 图片加载
* @param uri Image Uri
* @param target {@link Target}
* @param options {@link RequestOptions}
*/
public void loadImageGif(final String uri, final Target<GifDrawable> target, final RequestOptions options) {
if (mRequestManager != null) {
if (options != null) {
mRequestManager.asGif().load(uri).apply(options).into(target);
} else {
mRequestManager.asGif().load(uri).into(target);
}
}
}
public void recycle() {
targets.clear();
for (GifDrawable gifDrawable : gifDrawables) {
gifDrawable.setCallback(null);
gifDrawable.recycle();
}
gifDrawables.clear();
}
@Override public void draw(Canvas canvas) {
if (drawable != null) {
drawable.draw(canvas);
if (drawable instanceof GifDrawable) {
if (!((GifDrawable) drawable).isRunning()) {
((GifDrawable) drawable).start();
}
}
}
}
@Override
protected void onDraw(Canvas canvas) {
if (!(getDrawable() instanceof GifDrawable) && getDrawable() != null && (hasUniformBorder() || hasBorderRadius() || hasBorderWidth())) {
getDrawableWithBorder(canvas);
} else {
super.onDraw(canvas);
}
}
public void loadGifDrawable(Context context, @RawRes @DrawableRes int gifDrawableResId, ImageView iv, int playTimes) {
if (context == null || iv == null) {
return;
}
iv.setVisibility(View.VISIBLE);
theDisPlayImageView = new WeakReference<>(iv);//added by fee 2019-07-08: 将当前要显示的ImageView控件引用起来,但不适用本类用于给不同的ImageView加载
this.playTimes = playTimes;
//注:如果不是gif资源,则在asGif()时会抛异常
RequestBuilder<GifDrawable> requestBuilder =
Glide.with(context.getApplicationContext())
.asGif()
// .load(gifDrawableResId)
;
if (
playTimes >= 1 ||
loadCallback != null) {//指定了播放次数,则需要监听动画执行的结束
requestBuilder.listener(this)
;
}
RequestOptions options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
requestBuilder.apply(options)
// listener(this)
.load(gifDrawableResId)
.into(iv)
;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
CommonLog.e(TAG, "-->onLoadFailed() occur: " + e);
String exceptionInfo = "load fail";
if (e != null) {
exceptionInfo = e.getMessage();
}
loadCallback(false, false,null, 0, exceptionInfo);
return false;
}
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable>
animation) {
super.onResourceReady(resource, animation);
if (!autoplayGifs) {
resource.stop();
}
BadgedFourThreeImageView badgedImageView = (BadgedFourThreeImageView) getView();
if (resource instanceof GlideBitmapDrawable) {
Palette.from(((GlideBitmapDrawable) resource).getBitmap())
.clearFilters()
.generate(this);
} else if (resource instanceof GifDrawable) {
Bitmap image = ((GifDrawable) resource).getFirstFrame();
Palette.from(image).clearFilters().generate(this);
// look at the corner to determine the gif badge color
int cornerSize = (int) (56 * getView().getContext().getResources().getDisplayMetrics
().scaledDensity);
Bitmap corner = Bitmap.createBitmap(image,
image.getWidth() - cornerSize,
image.getHeight() - cornerSize,
cornerSize, cornerSize);
boolean isDark = ColorUtils.isDark(corner);
corner.recycle();
badgedImageView.setBadgeColor(ContextCompat.getColor(getView().getContext(),
isDark ? R.color.gif_badge_dark_image : R.color.gif_badge_light_image));
}
}
public static Bitmap getBitmap(GlideDrawable glideDrawable) {
if (glideDrawable instanceof GlideBitmapDrawable) {
return ((GlideBitmapDrawable) glideDrawable).getBitmap();
} else if (glideDrawable instanceof GifDrawable) {
return ((GifDrawable) glideDrawable).getFirstFrame();
}
return null;
}
public static void hybridImplementation(String u, final ImageView target, Context context, final Runnable callback) {
if (u.contains(".gif")) {
Glide.with(context).asGif().load(u)
.apply(getOpt())
.into(new ImageViewTarget<GifDrawable>(target) {
@Override
protected void setResource(GifDrawable resource) {
target.setImageDrawable(resource);
callback.run();
}
});
} else {
picassoImplementation(u, target, context, callback);
}
}
@Override
public void recycle() {
Glide.clear(this);
if (gifDrawableSoftReference != null) {
GifDrawable gifDrawable = gifDrawableSoftReference.get();
if (gifDrawable != null) {
gifDrawable.setCallback(null);
gifDrawable.stop();
}
}
}
@Override
public void onResourceReady(GifDrawable resource, GlideAnimation<? super GifDrawable> glideAnimation) {
if (!activityIsAlive()) {
return;
}
DrawableWrapper drawableWrapper = urlDrawableWeakReference.get();
if (drawableWrapper == null) {
return;
}
holder.setImageState(ImageHolder.ImageState.READY);
gifDrawableSoftReference = new SoftReference<>(resource);
Bitmap first = resource.getFirstFrame();
holder.setSize(first.getWidth(), first.getHeight());
drawableWrapper.setDrawable(resource);
if (rect != null) {
drawableWrapper.setBounds(rect);
} else {
if (!config.autoFix && config.imageFixCallback != null) {
config.imageFixCallback.onImageReady(holder, first.getWidth(), first.getHeight());
}
if (config.autoFix || holder.isAutoFix() || !holder.isInvalidateSize()) {
int width = getRealWidth();
int height = (int) ((float) first.getHeight() * width / first.getWidth());
drawableWrapper.setBounds(0, 0, width, height);
} else {
drawableWrapper.setBounds(0, 0, holder.getWidth(), holder.getHeight());
}
if (holder.isAutoPlay()) {
resource.setCallback(this);
resource.start();
resource.setLoopCount(GlideDrawable.LOOP_FOREVER);
}
}
resetText();
loadDone();
}