Android local image displayed via webview is blurry

后端 未结 3 1048
庸人自扰
庸人自扰 2021-01-19 18:06

I have a webview loading an image from the assets/ folder. The image is displayed zoomed 100% (or more) and does not have the same clarity as the real image has at 100%

3条回答
  •  醉酒成梦
    2021-01-19 18:30

    I found the solution to showing good quality images in a webview. (let it be known that I loathe working with the webview!)

    Root Cause: Out of the box, in a webview there's no concept of XXHDPI and XHDPI - if you do use those images on an XXHDPI or XHDPI device then the image is too damn large ! So you end up using HDPI/MDPI images... at least I did and then the images look blurred.

    Solution Description: In your HTML (I programmatically create it within the activity), enable scaling and then programmatically detect the logical density. Calculate the scale (i.e. 300% on a XXHDPI device) and put that value into your HTML otherwise your font will be TINY! Within your drawable resources, ensure you're using graphics that match the resolution of the device (i.e. XXHDPI images on an XXHDPI device) - this is a reminder to replace the MDPI images in your XXHDPI res folder.

    Coded Solution:

    // constants needed to put together a nice Android webview-friendly page
    private static final String HTML_STYLE = "";
    private static final String HTML_META = "";
    private static final String HTML_HEAD = "description"+HTML_META+HTML_STYLE+"";
    private static final String HTML_TAIL = "";
    
    // content to show in the webview
    final String strBody = "
    • stuff1
    • stuff2
    • stuff3

    "; // get the logical font size DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int iFontScale = (int) (displaymetrics.scaledDensity * 100.0f); // alter the HTML to programmatically insert the font scale final String strCompleteHTML = (HTML_HEAD+strBody+HTML_TAIL).replace("[TBD]", String.valueOf(iFontScale)); // configure the webview and load the HTML final WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setHorizontalScrollBarEnabled(false); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.loadDataWithBaseURL("file:///android_asset/", strCompleteHTML, "text/html", "utf-8", null);

提交回复
热议问题