12.4 显示动画GIF| Java Debug 笔记

363 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>

如何在自己的应用程序里显示动画GIF?

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

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

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

我的计划是将动画GIF分解为帧,并将每个帧作为可绘制对象添加到AnimationDrawable中。

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

回答1:

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

Paint p = new Paint();             
p.setAntiAlias(true);
setLayerType(LAYER_TYPE_SOFTWARE, p);

回答2:

<html style="margin: 0;">
<body style="margin: 0;">
<img src="name.gif" style="width: 100%; height: 100%" />
</body>
</html>
//声明如下
<WebView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="@+id/webView"
android:layout_gravity="center_horizontal" />

将如下代码放入你的oncreate()方法中

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

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


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