安卓-在Webview中加载GIF动画

4

我正在WebView中展示一个gif文件。

enter image description here

这个gif在我的网页加载完成之前都是可见的。

我是通过以下方式来实现的:

第一种方法:在Webview中加载gif

我将loading.gif放在asset文件夹中。

xml代码:

<WebView
    android:id="@+id/webview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="2dp"
    android:layout_centerHorizontal="true"/>

Java:

wv.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            WebView loading = (WebView)findViewById(R.id.webview1);
            loading.loadUrl("file:///android_asset/loading.GIF");
            loading.setBackgroundColor(Color.TRANSPARENT);
            loading.setVisibility(View.VISIBLE);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            WebView loading = (WebView)findViewById(R.id.webview1);
            loading.setVisibility(View.INVISIBLE);
        }

    });

第二种方法:在ImageView中加载gif帧

xml:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
    <item android:drawable="@drawable/frame1" android:duration="50" />
    <item android:drawable="@drawable/frame2" android:duration="50" />
    <item android:drawable="@drawable/frame3" android:duration="50" />
    etc...
</animation-list>

Java:

imageView.setBackgroundResource(R.drawable.movie);
AnimationDrawable anim = (AnimationDrawable) imageView.getBackground();
anim.start();

但是在这两种情况下动画都不够流畅。第二种方法要好一些。我只想知道是否有任何方法可以在不使用gif的情况下实现相同的效果?如果不可能,那么我想知道gif在所有像素密度下是否具有相同的大小。因为gif文件的尺寸是以px而不是以dp为单位的。

你用了什么来加载gif图片?你对Glide Google库有什么看法?对于gif的Webview或Glide,哪种方法更好? - Ravindra Kushwaha
你不需要加载框架,只需在WebView或ImageView中加载动画gif即可。我已经添加了一个答案。 - Jorgesys
1个回答

2
这是一个示例:

如何将 gif 加载到 WebView

创建带有 .gif 文件地址的 HTML:

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

将此文件存储到资产目录中:

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");

这是一个完整的示例,有两个选项(使用WebView或ImageView)来加载动画gif

enter image description here


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