2012-05-03 19 views

Respuesta

3

Usted puede utilizar este código para centrar la imagen en el centro de la pantalla en una vista Web:

//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      

    } 

He utilizado la etiqueta centro para centrar la imagen verticalmente y luego se usa el vspace etiqueta para dar el margen superior de la imagen. Ahora, el margen se calcula por: screenVierticalHeight/2-ImageVerticalHeight/Esperanza 2

esto ayuda

+1

¡Parece prometedor, compruebalo y cambia mi respuesta! ¡Gracias! – AndroidXTr3meN

0

Intente cargar un archivo HTML que incruste la imagen. Todo el diseño puede hacerse con estilos CSS estándar entonces.

+0

que hago, las imágenes es código HTML que carga una imagen de mi tarjeta SD – AndroidXTr3meN

+0

se puede colocar el código html? es difícil adivinar el problema de lo contrario. – alex

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

Esto coloca la imagen de la tarjeta SD en el centro de la vista web. Espero que esto ayude

+0

wowow that worksds la mitad del camino, gracias hasta ahora, pero se centra solo horizontal y no vertical. ¿Es posible centrarlo vertical? – AndroidXTr3meN

0

que tenía el mismo problema - centrado verticalmente en vista web. Esta solución funciona la mayor parte del tiempo ... tal vez puede ayudar un poco

   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"); 

       } 
+0

¿Y dónde debería ir este código> onCreate? – AndroidXTr3meN

0

Sé que esta respuesta es un poco tarde pero aquí es una opción sin javascript:

puede extender vista web y utilizar el protegido métodos computeHorizontalScrollRange() y computeVerticalScrollRange() para tener una idea del rango de desplazamiento máximo y sobre la base de que calculan la que desea scrollTo con computeHorizontalScrollRange()/2 - getWidth()/2 and de manera similar para verticales: computeVerticalScrollRange()/2 - getHeight()/2

mi único consejo sería para asegurarse de que la carga se ha completado antes de hacerlo, yo no he probado si esto funciona mientras las cosas se están cargando, pero no creo que así sea, ya que la vista web no tendrá su rango de desplazamiento correctamente configurado (ya que el contenido aún se está cargando)

ver: Android webview : detect scroll donde obtuve mucha de mi información de.

6

Lo hice con una combinación de xml y código. Tengo mi archivo gif almacenado en la carpeta de activos.

<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> 

@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; 
     } 
} 
0

Para mí que es trabajo:

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", ""); 
0
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);

Así que esto va a cargar su vista web con el texto en el centro