【Android】从无到有:手把手一步步使用android-gif-drawable包加载GIF动图

转载请注明出处,原文链接:https://blog.csdn.net/u013642500/article/details/80200129
【添加依赖】

首先需要添加android-gif-drawable依赖,请参考:【Android】实用教程:导入android-gif-drawable包,不用在GitHub下载(Android Studio 3.1.2)

【使用】

一、在layout中添加GifImageView控件,该控件既可以加载gif动态图,也可以加载jpg、png静态图。不需要设置src属性。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TestActivity">

    <pl.droidsonroids.gif.GifImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>


二、在java文件中,给GifImageView设置src属性,加载gif动态图。

1、获取GifImageView控件。

        GifImageView gifImageView = findViewById(R.id.image);

2、实例化GifDrawable对象,共有11种方法。

(1)Resouces文件
         源码:

	/**
	 * Creates drawable from resource.
	 *
	 * @param res Resources to read from
	 * @param id  resource id (raw or drawable)
	 * @throws NotFoundException    if the given ID does not exist.
	 * @throws IOException          when opening failed
	 * @throws NullPointerException if res is null
	 */
	public GifDrawable(@NonNull Resources res, @RawRes @DrawableRes int id) throws NotFoundException, IOException {
		this(res.openRawResourceFd(id));
		final float densityScale = GifViewUtils.getDensityScale(res, id);
		mScaledHeight = (int) (mNativeInfoHandle.getHeight() * densityScale);
		mScaledWidth = (int) (mNativeInfoHandle.getWidth() * densityScale);
	}

         示例:

            // Resources file
            GifDrawable gifFromAssets = new GifDrawable(getResources(), R.mipmap.timg);

(2)Assets文件
         源码:

	/**
	 * Creates drawable from asset.
	 *
	 * @param assets    AssetManager to read from
	 * @param assetName name of the asset
	 * @throws IOException          when opening failed
	 * @throws NullPointerException if assets or assetName is null
	 */
	public GifDrawable(@NonNull AssetManager assets, @NonNull String assetName) throws IOException {
		this(assets.openFd(assetName));
	}

         示例:

            // Assets file
            GifDrawable gifFromAssets = new GifDrawable(getAssets(), "timg.gif");

(3)文件路径
         源码:

	/**
	 * Constructs drawable from given file path.<br>
	 * Only metadata is read, no graphic data is decoded here.
	 * In practice can be called from main thread. However it will violate
	 * {@link StrictMode} policy if disk reads detection is enabled.<br>
	 *
	 * @param filePath path to the GIF file
	 * @throws IOException          when opening failed
	 * @throws NullPointerException if filePath is null
	 */
	public GifDrawable(@NonNull String filePath) throws IOException {
		this(new GifInfoHandle(filePath), null, null, true);
	}

         示例:

            // path to the GIF file
            GifDrawable gifFromPath = new GifDrawable("/path/timg.gif");

(4)File文件
         源码:

	/**
	 * Equivalent to {@code} GifDrawable(file.getPath())}
	 *
	 * @param file the GIF file
	 * @throws IOException          when opening failed
	 * @throws NullPointerException if file is null
	 */
	public GifDrawable(@NonNull File file) throws IOException {
		this(file.getPath());
	}

         示例:

            // the GIF file
            File gifFile = new File(getFilesDir(), "timg.gif");
            GifDrawable gifFromFile = new GifDrawable(gifFile);

(5)输入流 stream to read from
         源码:

	/**
	 * Creates drawable from InputStream.
	 * InputStream must support marking, IllegalArgumentException will be thrown otherwise.
	 *
	 * @param stream stream to read from
	 * @throws IOException              when opening failed
	 * @throws IllegalArgumentException if stream does not support marking
	 * @throws NullPointerException     if stream is null
	 */
	public GifDrawable(@NonNull InputStream stream) throws IOException {
		this(new GifInfoHandle(stream), null, null, true);
	}

(6)AssetFileDescriptor
         源码:

	/**
	 * Creates drawable from AssetFileDescriptor.
	 * Convenience wrapper for {@link GifDrawable#GifDrawable(FileDescriptor)}
	 *
	 * @param afd source
	 * @throws NullPointerException if afd is null
	 * @throws IOException          when opening failed
	 */
	public GifDrawable(@NonNull AssetFileDescriptor afd) throws IOException {
		this(new GifInfoHandle(afd), null, null, true);
	}

         示例:

            // Creates drawable from AssetFileDescriptor
            AssetFileDescriptor assetFileDescriptor = getAssets().openFd("timg.gif");
            GifDrawable gifFromAfd = new GifDrawable(assetFileDescriptor);

(7)FileDescriptor
         源码:

	/**
	 * Creates drawable from FileDescriptor
	 *
	 * @param fd source
	 * @throws IOException          when opening failed
	 * @throws NullPointerException if fd is null
	 */
	public GifDrawable(@NonNull FileDescriptor fd) throws IOException {
		this(new GifInfoHandle(fd), null, null, true);
	}

         示例:

            // Creates drawable from FileDescriptor
            FileDescriptor fileDescriptor = new RandomAccessFile("/path/timg.gif", "r").getFD();
            GifDrawable gifFromFd = new GifDrawable(fileDescriptor);

(8)raw GIF bytes
         源码:

	 * Creates drawable from byte array.<br>
	 * It can be larger than size of the GIF data. Bytes beyond GIF terminator are not accessed.
	 *
	 * @param bytes raw GIF bytes
	 * @throws IOException          if bytes does not contain valid GIF data
	 * @throws NullPointerException if bytes are null
	 */
	public GifDrawable(@NonNull byte[] bytes) throws IOException {
		this(new GifInfoHandle(bytes), null, null, true);
	}

(9)ByteBuffer
         源码:

	/**
	 * Creates drawable from {@link ByteBuffer}. Only direct buffers are supported.
	 * Buffer can be larger than size of the GIF data. Bytes beyond GIF terminator are not accessed.
	 *
	 * @param buffer buffer containing GIF data
	 * @throws IOException          if buffer does not contain valid GIF data or is indirect
	 * @throws NullPointerException if buffer is null
	 */
	public GifDrawable(@NonNull ByteBuffer buffer) throws IOException {
		this(new GifInfoHandle(buffer), null, null, true);
	}

(10)ContentResolver
           源码:

	/**
	 * Creates drawable from {@link android.net.Uri} which is resolved using {@code resolver}.
	 * {@link android.content.ContentResolver#openAssetFileDescriptor(android.net.Uri, String)}
	 * is used to open an Uri.
	 *
	 * @param uri      GIF Uri, cannot be null.
	 * @param resolver resolver used to query {@code uri}, can be null for file:// scheme Uris
	 * @throws IOException if resolution fails or destination is not a GIF.
	 */
	public GifDrawable(@Nullable ContentResolver resolver, @NonNull Uri uri) throws IOException {
		this(GifInfoHandle.openUri(resolver, uri), null, null, true);
	}

(11)InputSource
           源码:

	/**
	 * Creates drawable from {@link InputSource}.
	 *
	 * @param inputSource                The {@link InputSource} concrete subclass used to construct {@link GifDrawable}.
	 * @param oldDrawable                The old drawable that will be reused to save the memory. Can be null.
	 * @param executor                   The executor for rendering tasks. Can be null.
	 * @param isRenderingTriggeredOnDraw True if rendering of the next frame is scheduled after drawing current one, false otherwise.
	 * @param options                    Options controlling various GIF parameters.
	 * @throws IOException if input source is invalid.
	 */
	protected GifDrawable(@NonNull InputSource inputSource,
	                      @Nullable GifDrawable oldDrawable,
	                      @Nullable ScheduledThreadPoolExecutor executor,
	                      boolean isRenderingTriggeredOnDraw,
	                      @NonNull GifOptions options) throws IOException {

		this(inputSource.createHandleWith(options), oldDrawable, executor, isRenderingTriggeredOnDraw);
	}

3、设置GifImageView控件的src。

加载动态图:GifImageView 对象调用方法 setImageDrawable,参数为 GifDrawable 对象。

加载静态图:GifImageView 对象调用方法 setImageDrawable,参数为 Drawable 对象。

            // mipmap 中有动态图 timg.gif
            GifDrawable gifDrawable = new GifDrawable(getResources(), R.mipmap.timg);
            gifImageView.setImageDrawable(gifDrawable);

            // mipmap 中有静态图 ic_launcher.png
            Drawable drawable = getDrawable(R.mipmap.ic_launcher);
            gifImageView.setImageDrawable(drawable);
【注意】

GifDrawable类的对象读取静态图可能会报错。

本人尚属初学者,如有错误或疑问请评论提出,由衷感谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值