Display Animated GIF

后端 未结 30 2046
无人及你
无人及你 2020-11-22 02:11

I want to display animated GIF images in my aplication. As I found out the hard way Android doesn\'t support animated GIF natively.

However it can display animations

30条回答
  •  灰色年华
    2020-11-22 02:33

    For only android API (Android Pie)28 and +

    use AnimatedImageDrawable as

    // ImageView from layout
    val ima : ImageView = findViewById(R.id.img_gif)
    // create AnimatedDrawable 
    val decodedAnimation = ImageDecoder.decodeDrawable(
            // create ImageDecoder.Source object
            ImageDecoder.createSource(resources, R.drawable.tenor))
    // set the drawble as image source of ImageView
    ima.setImageDrawable(decodedAnimation)
    // play the animation
    (decodedAnimation as? AnimatedImageDrawable)?.start()
    

    XML code, add a ImageView

    
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_width="200dp"
        android:layout_height="200dp" />
    

    AnimatedImageDrawable is a child of Drawable and created by ImageDecoder.decodeDrawable

    ImageDecoder.decodeDrawable which further required the instance of ImageDecoder.Source created by ImageDecoder.createSource.

    ImageDecoder.createSource can only take source as a name, ByteBuffer, File, resourceId, URI, ContentResolver to create source object and uses it to create AnimatedImageDrawable as Drawable (polymorphic call)

    static ImageDecoder.Source  createSource(AssetManager assets, String fileName)
    static ImageDecoder.Source  createSource(ByteBuffer buffer)
    static ImageDecoder.Source  createSource(File file)
    static ImageDecoder.Source  createSource(Resources res, int resId)
    static ImageDecoder.Source  createSource(ContentResolver cr, Uri uri)
    

    Note: You can also create Bitmap using ImageDecoder#decodeBitmap.

    Output:

    AnimatedDrawable also supports resizing, frame and color manipulation

提交回复
热议问题