【Android】從無到有:手把手一步步使用android-gif-drawable包載入GIF動圖
【新增依賴】
首先需要新增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類的物件讀取靜態圖可能會報錯。
本人尚屬初學者,如有錯誤或疑問請評論提出,由衷感謝!