如何在Android中将GIF加载到ImageView背景中

4
这是我的代码,我正在从URL加载一个gif。我使用的是Glide库。但是这段代码没有运行,只显示了一个空白页面。
@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_background_gif);

            ImageView imageView = (ImageView) findViewById(R.id.gifImageView);

            //Glide.with(this).load(getResources().getDrawable(R.drawable.sample_img)).into(imageView);

            Glide.with(this)
                    .load("http://more-sky.com/data/out/6/IMG_105566.gif")
                    .into(new GlideDrawableImageViewTarget(imageView));

        }

你有互联网权限吗? - Vladyslav Matviienko
6个回答

2

试着使用这个

 Glide.with(context)
.load(imageUrl)
.asGif()
.placeholder(R.drawable.loading2)
.crossFade()
.into(imageView);

请查看以下链接,其中介绍了如何使用Glide图像加载和缓存库来显示GIF文件:https://dev59.com/yV0Z5IYBdhLWcg3wxCqQ - Ranjan


1

你也可以使用Picasso

Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

0

我使用Movie类来显示动画GIF,参考this page。下面是我创建的用于显示gif和调用方法的类。 从SDK 28开始,它已被弃用,建议使用AnimatedImageView。我两者都使用过,结果发现旧的、非官方的方式(使用Movie)更快、更可靠(AnimatedImageView有时会卡顿冻结)。

用于显示带有Movie的动画GIF的类

public class ShowGifView extends View {
    private Movie movie;
    private int gifImageDrawableId;
    private final Context ctx;
    private long gifStart = 0;

    public ShowGifView(Context context) {
        super(context);
        // Make the custom view focus.
        setFocusable(true);
        ctx = context;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        long now = System.currentTimeMillis();

        if (gifStart == 0) {
            gifStart = now;
        }

        if (movie != null) {
            // Get gif movie duration time.
            int duration = movie.duration();
            if (duration == 0) {
                duration = 1000;
            }

            // Get played frame percentage.
            int relTime = (int)((now - gifStart) % duration);

            // Set current gif frame time.
            movie.setTime(relTime);

            // Get custom view width and height.
            int width = this.getWidth();
            int height = this.getHeight();

            // Get gif image width and height.
            int movieWidth = movie.width();
            int movieHeight = movie.height();

            // Scale canvas size to fit the custom view.
            canvas.scale((float)width / movieWidth, (float)height / movieHeight);

            // Draw the gif image frame to custom view canvas.
            movie.draw(canvas, 1, 1);

            // This method will invoke onDraw method.
            invalidate();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(movie != null){
            int scale = heightMeasureSpec / movie.height();
            setMeasuredDimension(movie.width() * scale, movie.height() * scale);
        }else{
            setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
        }
    }

    public int getGifImageDrawableId() {
        return gifImageDrawableId;
    }

    public void setGifImageDrawableId(int gifImageDrawableId) {
        this.gifImageDrawableId = gifImageDrawableId;
    }

    // Call this method to read the drawable gif image to create movie object.
    public void drawGif()  {
        Resources resources = ctx.getResources();
        InputStream inputStream = resources.openRawResource(gifImageDrawableId);
        movie = Movie.decodeStream(inputStream);

        // Invalidate the view and invoke onDraw method.
        invalidate();
    }
}

调用此方法的代码:

    private View addAnimatedGif(ConstraintLayout lout, int animatedGif) {
        ShowGifView resultView = new ShowGifView(getApplicationContext());

        // Set Layer type to display animated GIF on all APIs
        resultView.setLayerType(View.LAYER_TYPE_SOFTWARE, new Paint());
        resultView.setGifImageDrawableId(animatedGif);
        resultView.drawGif();

        ConstraintSet cSet = new ConstraintSet();
        lout.addView(resultView);
        resultView.setId(View.generateViewId());
        int id = resultView.getId();

        cSet.clone(lout);
        cSet.connect(id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
        cSet.connect(id, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
        cSet.connect(id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
        cSet.connect(id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);

        cSet.applyTo(lout);

        return resultView;
    }

0

从 P OS,gif 现在直接被 Android 支持,并且很容易加载。
Java 代码(从文件加载):

ImageDecoder.Source source = ImageDecoder.createSource(new File(fileName));
AnimatedImageDrawable drawable = (AnimatedImageDrawable) ImageDecoder.decodeDrawable(source);
imageView.setImageDrawable(drawable);
drawable.start();

Kotlin 代码(从 assets 加载):

val source = ImageDecoder.createSource(assets, assetFileName)
val drawable = ImageDecoder.decodeDrawable(source)

imageView.setImageDrawable(drawable)
if (drawable is AnimatedImageDrawable) {
  drawable.start()
}

0

您可以使用WebView加载GIF图像。实现非常简单,而且效果很好。创建HTML页面。以下是代码:

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

创建assets文件夹并在其中创建html文件夹。将Gif图像和网页复制到html文件夹中。在xml中添加WebView。
MainActivity
webView = (WebView)findViewById(R.id.webView);
webView.setBackgroundColor(Color.TRANSPARENT); //for gif without background
webView.loadUrl("file:///android_asset/html/HTML_PAGE_NAME.html");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接