[英]Android: How to Display a Bitmap in a WebView?
由於內置的平移和縮放功能,我正在使用WebView來顯示類似地圖的圖像。 但是,我需要在地圖圖像上的某些點上疊加一些其他信息(標記等),並顯示所有這些信息。
因此,我將基本地圖圖像作為位圖,並將其他圖像疊加在其上(使用Canvas和更多位圖),從而為我提供了包含所有信息的最終位圖。 因為我需要在運行時編輯圖像,所以無法使用預制文件。 實現位圖的覆蓋不是問題,問題在於我不知道如何使用平移和縮放功能輕松顯示結果圖像。
有沒有一種方法可以使用WebView顯示位圖? 或其他建議?
使用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", "");
如果您想在Webview中加載圖片,則不需要占位符
您可以直接將dataurl加載到Web視圖中。 例如:
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
希望對別人有幫助! :-)
答案似乎是:不能,無法在Webview中顯示本地位圖對象而不將其保存到文件中。
您不需要位圖,只需其名稱就足夠了。 請嘗試以下操作:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.