java Android:WebView 在中心加载图像/内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10435219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:02:05  来源:igfitidea点击:

Android: WebView load image/content in center

javaandroidwebview

提问by AndroidXTr3meN

I have loaded an image with WebViewbut when it is zoomed out max the image place itself in the top left corner of my device. Is there anyway to load the image so it is displayed in center?

我已经加载了一个图像,WebView但是当它最大缩小时,图像将自身放置在我设备的左上角。无论如何要加载图像以使其显示在中心?

Cheers!

干杯!

采纳答案by Rahul Verma

You can use this code to center the image at the center of the screen in a WebView :

您可以使用此代码将图像居中在 WebView 的屏幕中心:

  //first you will need to find the dimensions of the screen 
  float width;
  float height;
  float currentHeight;
  WebView mWebView;

  //this function will set the current height according to screen orientation
  @Override
  public void onConfigurationChanged(Configuration newConfig){
          if(newConfig.equals(Configuration.ORIENTATION_LANDSCAPE)){

                currentHeight=width; 
                loadImage();                 

         }if(newConfig.equals(Configuration.ORIENTATION_PORTRAIT)){

                currentHeight=height;
                loadImage();

        }
    } 


  //call this function and it will place the image at the center
  public void load and center the image on screen(){

    mWebView=(WebView)findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);       
    mWebView.setBackgroundColor(0);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    currentHeight=height             //assuming that the phone
                                     //is held in portrait mode initially

         loadImage();        
  }
  public void loadImage(){
       Bitmap BitmapOfMyImage=BitmapFactory.decodeResource(Environment.getExternalStorgeDirectory().getAbsolutePath()+"yourFolder/myImageName.jpg");  

       mWebView.loadDataWithBaseURL("file:///"+Environment.getExternalStorgeDirectory().getAbsolutePath()
                                    +"yourFolder/","<html><center>
                                    <img src=\"myImageName.jpg\" vspace="
                                    +(currentHeight/2-(BitmapOfMyImage.getHeight()/2))+">
                                     </html>","text/html","utf-8","");
     //This loads the image at the center of thee screen                    

   }

I have used the center tag to center the image vertically and then used the vspace tag to give image top margin . Now the margin is calculated by : screenVierticalHeight/2-ImageVerticalHeight/2

我使用 center 标签将图像垂直居中,然后使用 vspace 标签提供图像上边距。现在边距由以下公式计算:screenVierticalHeight/2-ImageVerticalHeight/2

Hope this helps

希望这可以帮助

回答by user2765861

I did it with a combination of xml and code. I have my gif file stored in assets folder.

我是用xml和代码的组合来做的。我的 gif 文件存储在资产文件夹中。

Following is the xml layout code:

以下是xml布局代码:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<WebView
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true" />

</RelativeLayout>

Following is the java code:

下面是java代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewController());
    webView.loadDataWithBaseURL("file:///android_asset/","<html><center><img src=\"animation.gif\"></html>","text/html","utf-8","");
}

private class WebViewController extends WebViewClient {
     @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
}

回答by Rahul Verma

    mWebView.loadDataWithBaseURL("file:///"+Environment.getExternalStorgeDirectory().getAbsolutePath()+"yourFolder/","<html><center><img src=\"myImage.jpg\"></html>","text/html","utf-8","");

This places image from SDCard at center of the webView. I hope this helps

这会将来自 SDCard 的图像放置在 webView 的中心。我希望这有帮助

回答by sonal balekai

String html = "<html><head><style type='text/css'>html,body {margin: 0;padding: 0;width: 100%;height: 100%;}html {display: table;}body {display: table-cell;vertical-align: middle;text-align: center;}</style></head><body><p style=\"color:white\">+"you message"+</p></body></html>";

webView.loadData(html, "text/html; charset=UTF-8", null);

webView.loadData(html, "text/html; charset=UTF-8", null);

So this will load your webview with the text in center

所以这将加载您的 webview 中心的文本

回答by Gabriel Terry

For me that is work:

对我来说这就是工作:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "PICTURE FILE NAME";
File file = new File(path);
String html = "<style>img{height: 100%;max-width: 100%;}</style> <html><head></head><body><center><img src=\"" + imagePath + "\"></center></body></html>";
webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true); 
webView.getSettings().setLoadWithOverviewMode(true);
webView.loadDataWithBaseURL( "" ,  html, "text/html", "UTF-8", "");

回答by ununiform

I had the same problem - centering vertically in webview. This solution works most of the time... maybe it can help you a little

我遇到了同样的问题 - 在 webview 中垂直居中。这个解决方案大部分时间都有效......也许它可以帮助你

                int pheight = picture.getHeight();
                int vheight = view.getHeight();

                float ratio = (float) vheight / (float) pheight;

                System.out.println("pheight: " + pheight + "px");
                System.out.println("vheight: " + vheight + "px");
                System.out.println("ratio: " + ratio + "px");

                if (ratio > 0.5)
                {
                    return;
                }

                int diff = pheight - vheight;
                int diff2 = (int) ((diff * ratio) / 4);

                if (pheight > vheight)
                {
                    // scroll to middle of webview

                    currentPhotoWebview.scrollTo(0, diff2);
                    System.out.println("scrolling webview by " + diff2 + "px");

                }

回答by ara.hayrabedian

I know this answer's a little late but here's an option without javascript:

我知道这个答案有点晚了,但这里有一个没有 javascript 的选项:

you can extend WebView and use the protected methods computeHorizontalScrollRange()and computeVerticalScrollRange()to get an idea of the maximum scroll range and based on that calculate where you want to scrollTowith computeHorizontalScrollRange()/2 - getWidth()/2 andsimilarly for vertical: computeVerticalScrollRange()/2 - getHeight()/2

你可以扩展的WebView和使用受保护的方法computeHorizontalScrollRange(),并computeVerticalScrollRange()得到最大的滚动范围的想法,并根据您要的是计算scrollTocomputeHorizontalScrollRange()/2 - getWidth()/2 and类似垂直:computeVerticalScrollRange()/2 - getHeight()/2

my only advice would be to make sure that loading is complete before doing so, i haven't tested if this works while things are loading but i don't think it would as the webview won't yet have it's scroll range correctly set (as content is still being loaded)

我唯一的建议是在这样做之前确保加载完成,我还没有测试这在加载时是否有效,但我认为它不会,因为 webview 还没有正确设置它的滚动范围(因为内容仍在加载中)

see: Android webview : detect scrollwhere i got a lot of my info from.

请参阅:Android webview:检测滚动条,我从中获得了很多信息。

回答by alex

Try to load an HTML file that embeds the image instead. All the layout may done with standard css styles then.

尝试加载一个嵌入图像的 HTML 文件。所有的布局都可以用标准的 css 样式完成。