iOS按预期工作。我也试过将.gif添加到assets文件夹中(将BaseUrl设置为“file:/// android_asset”)没有运气。有任何想法吗?
imageHtml = "<center><body bgcolor =\""
+ GetBackgroundColorHex()
+ "\""
+ heightAndWidth
+ ">"
+ (!string.IsNullOrWhiteSpace(imageFileName)
? "<img src=\""
+ imageFileName
+ "\""
+ heightAndWidth
+ "/>"
: " ")
+ "</body></center>";
HtmlWebViewSource source = new HtmlWebViewSource()
{
Html = imageHtml
};
if (Device.RuntimePlatform == Device.Android && !string.IsNullOrWhiteSpace(imageFileName))
{
source.BaseUrl = "file:///android_res/drawable/";
}
Source = source;
这是我在输出中得到的错误:
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): Unable to open resource URL: file:///android_res/drawable/Loading.gif
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): java.lang.NoSuchFieldException: Loading
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): at java.lang.Class.getField(Class.java:1549)
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): at org.chromium.android_webview.AndroidProtocolHandler.getFieldId(AndroidProtocolHandler.java:40)
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): at org.chromium.android_webview.AndroidProtocolHandler.openResource(AndroidProtocolHandler.java:54)
12-11 02:08:00.256 E/AndroidProtocolHandler(12895): at org.chromium.android_webview.AndroidProtocolHandler.open(AndroidProtocolHandler.java:10)
您可以通过资产加载Android.Webkit.WebView
内容,而不是drawable。
这是Xamarin.Android
代码,用于解析图像以获得其宽度/高度,以确保保留纵横比并从Asset文件夹中显示它:
var src = "out.gif";
var backgroundColor = "#ff0000";
int imageWidth;
int imageHeight;
using (var stream = Assets.Open(src))
using (var options = new BitmapFactory.Options { InJustDecodeBounds = true })
{
await BitmapFactory.DecodeStreamAsync(stream, null, options);
imageWidth = options.OutWidth;
imageHeight = options.OutHeight;
}
var html = $"<body bgcolor={backgroundColor};\"><img src=\"{src}\" alt=\"A Gif file\" width=\"{imageWidth}\" height=\"{imageHeight}\" style=\"width: 100%; height: auto;\"/></body>";
webView.Settings.AllowFileAccessFromFileURLs = true;
webView.LoadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", "");
WebView
:var src = "image.gif";
var backgroundColor = "#ff0000";
int imageWidth = 300;
int imageHeight = 200;
var html = $"<body bgcolor={backgroundColor};\"><img src=\"{src}\" alt=\"A Gif file\" width=\"{imageWidth}\" height=\"{imageHeight}\" style=\"width: 100%; height: auto;\"/></body>";
webView.Source = new HtmlWebViewSource
{
Html = html
};
注意:image.gif
位于Android Assets(AndroidResource
)文件夹和iOS Resource文件夹(BundleResource
)中
将您的GIF文件保存在Assets文件夹中。这里“loading.gif”是文件名。
WebView webView=new WebView
{
Source = new HtmlWebViewSource
{
Html = $"<body\"><img src=\"loading.gif\"/></body>"
}
};
Content = webView;