I have loaded an image with WebView
but 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?
Cheers!
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);
So this will load your webview with the text in center
You can use this code to center the image at the center of the screen in a 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
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With