2011-04-04 17 views
47

Necesito convertir una vista a un mapa de bits para obtener una vista previa de mi vista y guardarla como una imagen. Intenté usar el siguiente código, pero crea una imagen en blanco. No puedo entender dónde cometí un error.Convertir vista a mapa de bits en Android

View viewToBeConverted; Bitmap viewBitmap = Bitmap.createBitmap(viewToBeConverted.getWidth(), viewToBeConverted.getHeight(),Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(viewBitmap); 
viewToBeConverted.draw(canvas); 
savephoto(“f1”, viewBitmap); 

//// public void savephoto(String filename,Bitmap bit)  
    { 
      File newFile = new File(Environment.getExternalStorageDirectory() + Picture_Card/"+ filename+ ".PNG"); 
       try 
{ 
        newFile.createNewFile();     
try 
{ 
         FileOutputStream pdfFile = new FileOutputStream(newFile);            Bitmap bm = bit;       ByteArrayOutputStream baos = new ByteArrayOutputStream();       bm.compress(Bitmap.CompressFormat.PNG,100, baos);              byte[] bytes = baos.toByteArray();       
pdfFile.write(bytes);            
     pdfFile.close();     
} 
catch (FileNotFoundException e) 
{       //  

    }    
    } catch (IOException e) 
{     //   
    }  
    } 

Respuesta

123

aquí está mi solución:

public static Bitmap getBitmapFromView(View view) { 
     //Define a bitmap with the same size as the view 
     Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); 
     //Bind a canvas to it 
     Canvas canvas = new Canvas(returnedBitmap); 
     //Get the view's background 
     Drawable bgDrawable =view.getBackground(); 
     if (bgDrawable!=null) 
      //has background drawable, then draw it on the canvas 
      bgDrawable.draw(canvas); 
     else 
      //does not have background drawable, then draw white background on the canvas 
      canvas.drawColor(Color.WHITE); 
     // draw the view on the canvas 
     view.draw(canvas); 
     //return the bitmap 
     return returnedBitmap; 
    } 

Enjoy :)

+4

Esta debería ser la respuesta aceptada –

+0

Gil SH, ¿puede describir el fragmento de arriba? –

+0

OK, lo edité y agregué comentarios –

27

La solución más votada no funcionó para mí, porque mi opinión es un ViewGroup (se han inflado de un LayoutInflater). Necesitaba llamar a view.measure para forzar que se calcule el tamaño de la vista para obtener el tamaño de vista correcto con view.getMeasuredWidth (Height).

public static Bitmap getBitmapFromView(View view) { 
    view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); 
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), 
      Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    view.draw(canvas); 
    return bitmap; 
} 
+0

¡Muchas gracias! – Dehumanizer

+0

Funciona en mi aplicación. ¡Gracias! – lovefish

2

Todas las respuestas que utilicen el dibujo en el lienzo no funcionarán con GLSurfaceView.

Para capturar el contenido de un GLSurfaceView en un mapa de bits, debe considerar implementar un método personalizado con gl.glReadPixels dentro de Renderer::onDrawFrame().

Se ha publicado un fragmento de solución here.

Cuestiones relacionadas