简体   繁体   中英

How to make gif images to fit WebView on Android

I'm using webview to display gif images, but the problem is, the webview windows doesn't fit the width of gif, there's always some blank space to the right of the gif.

Right now I have to manually set the width and try to keep the width of my gifs, but it's strange that the height always fit the gifs

        int w = 115;//image.getWidth();
        LayoutParams lp = holder.wv.getLayoutParams();    
        lp.width= (int) (w * context.getResources().getDisplayMetrics().density);
        holder.wv.setLayoutParams(lp); 

        holder.wv.loadUrl("file:///android_asset/" + text.substring(1, text.length()-1) + ".gif");
        holder.wv.setVisibility(View.VISIBLE);

Webview in xml layout

   <WebView
      android:id="@+id/wv"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" 
      android:layout_margin="2sp"
      android:gravity="center_vertical|center_horizontal"
      android:visibility="gone"/>

There is nothing wrong with the gifs, they don't have the trailing white space

Here is what it looks like on the device

在此处输入图片说明

here is the original gif

在此处输入图片说明

I think the best way is to wrap gif in HTML and scale it using CSS:

String gif_url = "file:///android_asset/" + text.substring(1, text.length()-1) + ".gif";
String html = "<html><body><img style=\"width: 100%\" src=\"" + gif_url + "\"></body></html>";
holder.wv.loadData(html);

我不得不手动编辑gif大小以使其适合窗口,这不是一个聪明的方法,但这是唯一的解决方案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM