首页 文章

显示动画GIF

提问于
浏览
232

我想在我的应用程序中显示动画GIF图像 . 正如我发现的那样,Android本身并不支持动画GIF .

但是它可以使用AnimationDrawable显示动画:

Develop > Guides > Images & Graphics > Drawables Overview

该示例使用在应用程序资源中保存为帧的动画,但我需要的是直接显示动画gif .

我的计划是将动画GIF分解为帧并将每个帧添加为可绘制到AnimationDrawable .

有谁知道如何从动画GIF中提取帧并将它们转换为Drawable

29 回答

  • 4

    UPDATE:

    使用滑行:

    dependencies {
      implementation 'com.github.bumptech.glide:glide:4.0.0'
    }
    

    用法:

    Glide.with(context).load(GIF_URI).into(new GlideDrawableImageViewTarget(IMAGE_VIEW));
    

    见文档

  • 21

    Android实际上可以使用android.graphics.Movie类解码和显示动画GIF .

    这没有太多记录,但是在SDK Reference . 此外,它在Samples in ApiDemos in BitmapDecode示例中使用了一些动画标志 .

  • 5

    也把(main / assets / htmls / name.gif)[用这个html调整到大小]

    <html style="margin: 0;">
    <body style="margin: 0;">
    <img src="name.gif" style="width: 100%; height: 100%" />
    </body>
    </html>
    

    在你的Xml中声明例如这样(main / res / layout / name.xml):[你定义大小,例如]

    <WebView
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:id="@+id/webView"
    android:layout_gravity="center_horizontal" />
    

    在您的Activity中将下一个代码放在onCreate中

    web = (WebView) findViewById(R.id.webView); 
    web.setBackgroundColor(Color.TRANSPARENT); //for gif without background
    web.loadUrl("file:///android_asset/htmls/name.html");
    

    如果要动态加载,则必须使用数据加载webview:

    // or "[path]/name.gif" (e.g: file:///android_asset/name.gif for resources in asset folder), and in loadDataWithBaseURL(), you don't need to set base URL, on the other hand, it's similar to loadData() method.
    String gifName = "name.gif";
    String yourData = "<html style=\"margin: 0;\">\n" +
            "    <body style=\"margin: 0;\">\n" +
            "    <img src=" + gifName + " style=\"width: 100%; height: 100%\" />\n" +
            "    </body>\n" +
            "    </html>";
    // Important to add this attribute to webView to get resource from outside.
    webView.getSettings().setAllowFileAccess(true);
    
    // Notice: should use loadDataWithBaseURL. BaseUrl could be the base url such as the path to asset folder, or SDCard or any other path, where your images or the other media resides related to your html
    webView.loadDataWithBaseURL("file:///android_asset/", yourData, "text/html", "utf-8", null);
    // Or if you want to load image from SD card or where else, here is the idea.
    String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
    webView.loadDataWithBaseURL(base + '/', yourData, "text/html", "utf-8", null);
    

    建议:更好的加载gif与静态图像更多信息检查https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

    就是这样,我希望你能提供帮助 .

  • 1

    我通过将 gif 动画分割成帧然后将其保存到手机来解决了这个问题,所以我不必在Android中处理它 .

    然后我将每一帧下载到手机上,从中创建Drawable然后创建 AnimationDrawable - 非常类似于我的问题中的示例

  • 8

    我找到了一个非常简单的方法,这里有一个简单的工作示例

    display animated widget

    在开始工作之前,在代码中有一些要做的事情

    在下面的

    @Override
        public void onCreate(Bundle savedInstanceState){    
            super.onCreate(savedInstanceStated);   
            setContentView(new MYGIFView());
        }    
    }
    

    只是替换

    setContentView(new MYGIFView());
    

    setContentView(new MYGIFView(this));
    

    和IN

    public GIFView(Context context) {
        super(context);
    

    提供您自己的gif动画文件

    is = context.getResources().openRawResource(R.drawable.earth);
        movie = Movie.decodeStream(is);
    }
    

    取代第一线

    public MYGIFView(Context context) {
    

    根据 class 名称......

    完成这些小改动之后它应该对我有用......

    希望这个帮助

  • 2

    在Android上显示动画GIF的方法:

    • 电影课 . 如上所述,它是相当错误的 .

    • WebView . 它使用起来非常简单并且通常有效 . 但有时它开始行为不端,而且它已经开始行动了 . 此外,您不能在任何类型的列表视图中使用多个实例,因为它会对您的内存起作用 . 不过,您可能会将其视为主要方法 .

    • 自定义代码,用于将GIF解码为位图并将其显示为Drawable或ImageView . 我会提到两个库:

    https://github.com/koral--/android-gif-drawable - 解码器在C中实现,因此它非常有效 .

    https://code.google.com/p/giffiledecoder - 解码器是用Java实现的,因此更容易使用 . 即使对于大文件,仍然相当有效 .

    您还可以找到许多基于GifDecoder类的库 . 这也是一个基于Java的解码器,但它的工作原理是将整个文件加载到内存中,因此它只适用于小文件 .

  • 4

    我很难让Android动画gif工作 . 我只跟着两个工作:

    WebView工作正常,非常简单,但问题是它使视图加载速度变慢,应用程序在一秒左右没有响应 . 我不喜欢那样 . 所以我尝试了不同的方法(DID NOT WORK):

    • ImageViewEx已弃用!

    • picasso未加载GIF动画

    • android-gif-drawable看起来很棒,但它在我的项目中引起了一些有线NDK问题 . 它导致我的本地NDK库停止工作,我无法修复它

    我有一些来回 Ion ;最后,我有它工作,它真的很快:-)

    Ion.with(imgView)
      .error(R.drawable.default_image)
      .animateGif(AnimateGifMode.ANIMATE)
      .load("file:///android_asset/animated.gif");
    
  • -1

    使用ImageViewEx,一个使用gif的库就像使用_1212041一样简单 .

  • 16

    Glide

    适用于Android的Image Loader Library,由Google推荐 .

    • Glide与毕加索非常相似,但这比毕加索要快得多 .

    • Glide比毕加索消耗的内存更少 .

    What that Glide has but Picasso doesn't

    将GIF动画加载到简单的ImageView的功能可能是Glide最有趣的功能 . 是的,你不能用毕加索做到这一点 .
    enter image description here
    Some important links-

  • 1

    没人提到IonGlide库 . 他们工作得很好 .

    与WebView相比,它更容易处理 .

  • 5

    我已经成功地提出了within this article这个名为 GifMovieView 的类的解决方案,该类渲染了 View 然后可以显示或者添加到特定的 ViewGroup . 查看指定文章第2部分和第3部分中介绍的其他方法 .

    这种方法的唯一缺点是对电影的抗锯齿效果不是那么好(必须是使用"shady" Android Movie 类的副作用) . 然后,最好在动画GIF中将背景设置为纯色 .

  • 9

    试试这个,下面是代码显示进度条中的gif文件

    loading_activity.xml(在布局文件夹中)

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff" >
    
        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/custom_loading"
            android:visibility="gone" />
    
    </RelativeLayout>
    

    custom_loading.xml(在drawable文件夹中)

    在这里我把black_gif.gif(在drawable文件夹中),你可以把你自己的gif放在这里

    <?xml version="1.0" encoding="utf-8"?>
    <animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:drawable="@drawable/black_gif"
        android:pivotX="50%"
        android:pivotY="50%" />
    

    LoadingActivity.java(在res文件夹中)

    public class LoadingActivity extends Activity {
    
        ProgressBar bar;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_loading);
            bar = (ProgressBar) findViewById(R.id.progressBar);
            bar.setVisibility(View.VISIBLE);
    
        }
    
    }
    
  • 0

    关于BitmapDecode示例的一些想法......基本上它使用了android.graphics中的古老而无特征的Movie类 . 在最近的API版本中,您需要关闭硬件加速,as described here . 否则,这对我来说是分段的 .

    <activity
                android:hardwareAccelerated="false"
                android:name="foo.GifActivity"
                android:label="The state of computer animation 2014">
    </activity>
    

    这是仅使用GIF部分缩短的BitmapDecode示例 . 你必须制作自己的小工具(视图)并自己绘制 . 不像ImageView那么强大 .

    import android.app.Activity;
    import android.content.Context;
    import android.graphics.*;
    import android.os.*;
    import android.view.View;
    
    public class GifActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new GifView(this));
        }
    
        static class GifView extends View {
            Movie movie;
    
            GifView(Context context) {
                super(context);
                movie = Movie.decodeStream(
                        context.getResources().openRawResource(
                                R.drawable.some_gif));
            }
            @Override
            protected void onDraw(Canvas canvas) {   
                if (movie != null) {
                    movie.setTime(
                        (int) SystemClock.uptimeMillis() % movie.duration());
                    movie.draw(canvas, 0, 0);
                    invalidate();
                }
            }
        }
    }
    

    另外2个方法,一个用ImageView另一个用WebView可以在this fine tutorial中找到 . ImageView方法使用来自Google Code的Apache许可android-gifview .

  • 181

    @PointerNull提供了很好的解决方案,但并不完美 . 它在某些具有大文件的设备上不起作用,并且在前ICS版本上显示带有增量帧的错误Gif动画 . 我找到了没有这个错误的解决方案 . 它是具有原生解码的库,可绘制:koral's android-gif-drawable .

  • 1

    将它放入WebView,它必须能够正确显示它,因为默认浏览器支持gif文件 . (Froyo,如果我没有记错的话)

  • 0

    Glide 4.6

    1. To Load gif

    GlideApp.with(context)
                .load(R.raw.gif) // or url
                .into(imageview);
    

    2. To get the file object

    GlideApp.with(context)
                    .asGif()
                    .load(R.raw.gif) //or url
                    .into(new SimpleTarget<GifDrawable>() {
                        @Override
                        public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
    
                            resource.start();
                          //resource.setLoopCount(1);
                            imageView.setImageDrawable(resource);
                        }
                    });
    
  • 0

    仅适用于Android API(Android Pie)28和

    使用AnimatedImageDrawable作为

    // 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代码,添加一个ImageView

    <ImageView
        android:id="@+id/img_gif"
        android:background="@drawable/ic_launcher_background" <!--Default background-->
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_width="200dp"
        android:layout_height="200dp" />
    

    AnimatedImageDrawable 是Drawable的子项,由 ImageDecoder.decodeDrawable 创建

    ImageDecoder.decodeDrawable 进一步需要 ImageDecoder.createSource 创建的 ImageDecoder.Source 实例 .

    ImageDecoder.createSource 只能将source作为名称,ByteBuffer,File,resourceId,URI,ContentResolver来创建源对象并使用它来创建 AnimatedImageDrawable 作为 Drawable (多态调用)

    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)
    

    注意:您也可以使用ImageDecoder#decodeBitmap创建 Bitmap .

    输出:

    AnimatedDrawable also supports resizing, frame and color manipulation

  • 6

    我认为处理gif文件的更好的库是this one: by koral

    用它和我'm successful and this library is dedicated to GIF' S;但是 picasso and glidegeneral purpose 图像框架;所以我认为这个库的开发人员完全专注于gif文件

  • 0

    使用壁画 . 这是怎么做的:

    http://frescolib.org/docs/animations.html

    这是样本的回购:

    https://github.com/facebook/fresco/tree/master/samples/animation

    当心壁画不支持包装内容!

  • 0

    只想添加Movie类现已弃用 .

    此类在API级别P中已弃用 .

    建议使用它

    AnimatedImageDrawable

    Drawable用于绘制动画图像(如GIF) .

  • 27

    您可以使用此链接中的GifAnimationDrawable库 - https://github.com/Hipmob/gifanimateddrawable,并将任何gif转换为AnimationDrawable . 请享用 :)

  • 0
    public class Test extends GraphicsActivity {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
      }
    
      private static class SampleView extends View {
        private Bitmap mBitmap;
        private Bitmap mBitmap2;
        private Bitmap mBitmap3;
        private Bitmap mBitmap4;
        private Drawable mDrawable;
    
        private Movie mMovie;
        private long mMovieStart;
    
        // Set to false to use decodeByteArray
        private static final boolean DECODE_STREAM = true;
    
        private static byte[] streamToBytes(InputStream is) {
          ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
          byte[] buffer = new byte[1024];
          int len;
          try {
            while ((len = is.read(buffer)) >= 0) {
              os.write(buffer, 0, len);
            }
          } catch (java.io.IOException e) {
          }
          return os.toByteArray();
        }
    
        public SampleView(Context context) {
          super(context);
          setFocusable(true);
    
          java.io.InputStream is;
          is = context.getResources().openRawResource(R.drawable.icon);
    
          BitmapFactory.Options opts = new BitmapFactory.Options();
          Bitmap bm;
    
          opts.inJustDecodeBounds = true;
          bm = BitmapFactory.decodeStream(is, null, opts);
    
          // now opts.outWidth and opts.outHeight are the dimension of the
          // bitmap, even though bm is null
    
          opts.inJustDecodeBounds = false; // this will request the bm
          opts.inSampleSize = 4; // scaled down by 4
          bm = BitmapFactory.decodeStream(is, null, opts);
    
          mBitmap = bm;
    
          // decode an image with transparency
          is = context.getResources().openRawResource(R.drawable.icon);
          mBitmap2 = BitmapFactory.decodeStream(is);
    
          // create a deep copy of it using getPixels() into different configs
          int w = mBitmap2.getWidth();
          int h = mBitmap2.getHeight();
          int[] pixels = new int[w * h];
          mBitmap2.getPixels(pixels, 0, w, 0, 0, w, h);
          mBitmap3 = Bitmap.createBitmap(pixels, 0, w, w, h,
              Bitmap.Config.ARGB_8888);
          mBitmap4 = Bitmap.createBitmap(pixels, 0, w, w, h,
              Bitmap.Config.ARGB_4444);
    
          mDrawable = context.getResources().getDrawable(R.drawable.icon);
          mDrawable.setBounds(150, 20, 300, 100);
    
          is = context.getResources().openRawResource(R.drawable.animated_gif);
    
          if (DECODE_STREAM) {
            mMovie = Movie.decodeStream(is);
          } else {
            byte[] array = streamToBytes(is);
            mMovie = Movie.decodeByteArray(array, 0, array.length);
          }
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
          canvas.drawColor(0xFFCCCCCC);
    
          Paint p = new Paint();
          p.setAntiAlias(true);
    
          canvas.drawBitmap(mBitmap, 10, 10, null);
          canvas.drawBitmap(mBitmap2, 10, 170, null);
          canvas.drawBitmap(mBitmap3, 110, 170, null);
          canvas.drawBitmap(mBitmap4, 210, 170, null);
    
          mDrawable.draw(canvas);
    
          long now = android.os.SystemClock.uptimeMillis();
          if (mMovieStart == 0) { // first time
            mMovieStart = now;
          }
          if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
              dur = 1000;
            }
            int relTime = (int) ((now - mMovieStart) % dur);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()
                - mMovie.height());
            invalidate();
          }
        }
      }
    }
    
    class GraphicsActivity extends Activity {
      // set to true to test Picture
      private static final boolean TEST_PICTURE = false;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      }
    
      @Override
      public void setContentView(View view) {
        if (TEST_PICTURE) {
          ViewGroup vg = new PictureLayout(this);
          vg.addView(view);
          view = vg;
        }
    
        super.setContentView(view);
      }
    }
    
    class PictureLayout extends ViewGroup {
      private final Picture mPicture = new Picture();
    
      public PictureLayout(Context context) {
        super(context);
      }
    
      public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      @Override
      public void addView(View child) {
        if (getChildCount() > 1) {
          throw new IllegalStateException(
              "PictureLayout can host only one direct child");
        }
    
        super.addView(child);
      }
    
      @Override
      public void addView(View child, int index) {
        if (getChildCount() > 1) {
          throw new IllegalStateException(
              "PictureLayout can host only one direct child");
        }
    
        super.addView(child, index);
      }
    
      @Override
      public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
          throw new IllegalStateException(
              "PictureLayout can host only one direct child");
        }
    
        super.addView(child, params);
      }
    
      @Override
      public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
          throw new IllegalStateException(
              "PictureLayout can host only one direct child");
        }
    
        super.addView(child, index, params);
      }
    
      @Override
      protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);
      }
    
      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();
    
        int maxHeight = 0;
        int maxWidth = 0;
    
        for (int i = 0; i < count; i++) {
          final View child = getChildAt(i);
          if (child.getVisibility() != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
          }
        }
    
        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();
    
        Drawable drawable = getBackground();
        if (drawable != null) {
          maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
          maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }
    
        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
            resolveSize(maxHeight, heightMeasureSpec));
      }
    
      private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx,
          float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
      }
    
      @Override
      protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();
    
        int x = getWidth() / 2;
        int y = getHeight() / 2;
    
        if (false) {
          canvas.drawPicture(mPicture);
        } else {
          drawPict(canvas, 0, 0, x, y, 1, 1);
          drawPict(canvas, x, 0, x, y, -1, 1);
          drawPict(canvas, 0, y, x, y, 1, -1);
          drawPict(canvas, x, y, x, y, -1, -1);
        }
      }
    
      @Override
      public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
      }
    
      @Override
      protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();
    
        for (int i = 0; i < count; i++) {
          final View child = getChildAt(i);
          if (child.getVisibility() != GONE) {
            final int childLeft = getPaddingLeft();
            final int childTop = getPaddingTop();
            child.layout(childLeft, childTop,
                childLeft + child.getMeasuredWidth(),
                childTop + child.getMeasuredHeight());
    
          }
        }
      }
    }
    
  • 7

    将动画GIF加载到我们的Android应用程序有两种选择

    1)使用Glide将gif加载到 ImageView 中 .

    String urlGif = "https://cdn.dribbble.com/users/263558/screenshots/1337078/dvsd.gif";
        //add Glide implementation into the build.gradle file.
        ImageView imageView = (ImageView)findViewById(R.id.imageView);
        Uri uri = Uri.parse(urlGif);
        Glide.with(getApplicationContext()).load(uri).into(imageView);
    

    2)使用html将gif加载到 WebView

    使用.gif文件的地址创建html:

    <html style="margin: 0;">
    <body style="margin: 0;">
    <img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
    </body>
    </html>
    

    将此文件存储到assets目录中:

    enter image description here

    将此html加载到应用程序的WebView中:

    WebView webView =  (WebView)findViewById(R.id.webView);
        webView = (WebView) findViewById(R.id.webView);
        webView.loadUrl("file:///android_asset/html/webpage_gif.html");
    

    赫雷斯是complete example of this two options .

    enter image description here

  • 2

    首先,Android浏览器应支持动画GIF . 如果没有,那就是一个错误!看看问题跟踪器 .

    如果您在浏览器之外显示这些动画GIF,则可能是另一个故事 . 要做你想要的就需要支持动画GIF解码的外部库 .

    第一个调用端口是查看Java2D或JAI(Java高级成像)API,但如果Android Dalvik支持您应用程序中的这些库,我会感到非常惊讶 .

  • 7

    与@Leonti所说的相似,但更深入一点:

    我为解决同样的问题所做的是打开GIMP,隐藏除了一个之外的所有层,将其导出为自己的图像,然后隐藏该层并取消隐藏下一个等等,直到我为每个层都有单独的资源文件 . 然后我可以将它们用作AnimationDrawable XML文件中的框架 .

  • 2

    我通过在框架中拆分gif并使用标准的android动画来解决这个问题

  • 41

    我为在应用程序中显示GIF而做的事情 . 我扩展了ImageView,以便人们可以自由使用它的属性 . 它可以显示来自url或assets目录的gif . 该库还使扩展类很容易从它继承并扩展它以支持不同的方法来初始化gif .

    https://github.com/Gavras/GIFView

    还有一点github页面上的指南 .

    它也发布在Android阿森纳:

    https://android-arsenal.com/details/1/4947

    使用示例:

    来自XML:

    <com.whygraphics.gifview.gif.GIFView xmlns:gif_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/main_activity_gif_vie"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:scaleType="center"
            gif_view:gif_src="url:http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif" />
    

    在活动中:

    GIFView mGifView = (GIFView) findViewById(R.id.main_activity_gif_vie);
    
        mGifView.setOnSettingGifListener(new GIFView.OnSettingGifListener() {
                    @Override
                    public void onSuccess(GIFView view, Exception e) {
                        Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
                    }
    
                    @Override
                    public void onFailure(GIFView view, Exception e) {
    
            }
    });
    

    以编程方式设置gif:

    mGifView.setGifResource("asset:gif1");
    
  • -8

    最简单的方法 - 可以考虑以下代码

    我们可以利用Imageview setImageResource,参考下面的代码相同 .

    如果你有gif的多个分割图像,下面的代码可用于显示像gif incase的图像 . 只需将gif从在线工具拆分为单独的png,然后将图像放入drawable中,如下所示

    image_1.png,image_2.png等

    让处理程序动态更改图像 .

    int imagePosition = 1;
        Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                public void run() {
                    updateImage();
                }
            };
    
    
    
    
        public void updateImage() {
    
                    appInstance.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
                            gifImageViewDummy.setImageResource(resId);
                            imagePosition++;
        //Consider you have 30 image for the anim
                            if (imagePosition == 30) {
    //this make animation play only once
                                handler.removeCallbacks(runnable);
    
                            } else {
        //You can define your own time based on the animation
                                handler.postDelayed(runnable, 50);
                            }
    
    //to make animation to continue use below code and remove above if else
    // if (imagePosition == 30)
    //imagePosition = 1;
    // handler.postDelayed(runnable, 50);
    // 
                        }
                    });
                  }
    
  • 0

    直接从URL到应用程序布局显示动画GIF的简单方法是使用WebView类 .

    第1步: In your layout XML

    <WebView
    android:id="@+id/webView"
    android:layout_width="50dp"
    android:layout_height="50dp"
    />
    

    第2步: In your Activity

    WebView wb;
    wb = (WebView) findViewById(R.id.webView);
    wb.loadUrl("https://.......);
    

    第3步: In your Manifest.XML make Internet permission

    <uses-permission android:name="android.permission.INTERNET" />
    

    第4步: In case you want to make your GIF background transparent and make GIF fit to your Layout

    wb.setBackgroundColor(Color.TRANSPARENT);
    wb.getSettings().setLoadWithOverviewMode(true);
    wb.getSettings().setUseWideViewPort(true);
    

相关问题