Android:如何在WebView中显示位图?

时间:2012-06-01 11:14:03

标签: android webview bitmap

由于内置的​​平移和缩放功能,我使用WebView显示类似地图的图像。但是,我需要在地图图像的某些点上叠加一些其他信息(标记等),并显示所有这些信息。

所以我将我的基本地图图像作为位图,并将其他图像叠加在其上(使用Canvas和更多位图),给我一个包含所有信息的最终位图。因为我需要在运行时编辑图像,所以我不能使用预制文件。实现位图的重叠不是问题,问题是我不知道如何使用平移和缩放功能轻松显示生成的图像。

有没有办法使用WebView显示位图?还是其他任何建议?

5 个答案:

答案 0 :(得分:23)

使用itsrajesh4uguys中的链接,我创建了这段代码:

// Desired Bitmap and the html code, where you want to place it
Bitmap bitmap = YOUR_BITMAP;
String html="<html><body><img src='{IMAGE_PLACEHOLDER}' /></body></html>";

// Convert bitmap to Base64 encoded image for web
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
    String image = "data:image/png;base64," + imgageBase64;

// Use image for the img src parameter in your html and load to webview
html = html.replace("{IMAGE_PLACEHOLDER}", image);
webview.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");

答案 1 :(得分:2)

如果您想在webview中加载图片

,则不需要占位符

您可以直接在webview中加载dataurl。 例如:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
    String dataURL= "data:image/png;base64," + imgageBase64;

webview.loadUrl(dataURL); //pass the bitmap base64 dataurl in URL parameter

希望它能帮到别人! : - )

答案 2 :(得分:1)

通常在webview中我们可以使用html标签设置图像..这不会产生任何问题。

以任何方式使用此链接进行示例问答

Why Bitmap to Base64 String showing black background on webview in android?

答案 3 :(得分:1)

答案似乎是:不可以,在webview中显示本地位图对象而不将其保存到文件中是不可能的。

答案 4 :(得分:-1)

你不需要Bitmap,只需它的名字即可。请尝试以下方法:

html = "<html><img src=\"" + imageUrl
                        + "\"></html>";
final WebView webView = (WebView) view
                    .findViewById(R.id.yourWebView);
wvImageView.getSettings().setJavaScriptEnabled(true);
wvImageView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

这应该在WebView上显示您的图像。 如果您想提供缩放功能,请尝试以下方法:

webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);