2011-04-04 46 views
47

我需要将视图转换为位图才能预览我的视图并将其保存为图像。我尝试使用下面的代码,但它创建一个空白图像。我无法理解我犯了什么错误。将视图转换为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) 
{     //   
    }  
    } 

回答

123

这里是我的解决方案:

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

享受:)

+4

这应该是被接受的答案 – 2013-06-26 15:05:20

+0

Gil SH,请您描述上面的代码片段? – 2013-08-28 09:48:33

+0

好的,我编辑它,并添加评论 – 2013-09-08 18:33:15

27

最投票的解决方案并没有为我工作,因为我的看法是一个ViewGroup中(已经从LayoutInflater膨胀)。我需要调用view.measure来强制计算视图大小,以便通过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

非常感谢! – Dehumanizer 2015-08-31 01:43:46

+0

它适用于我的应用程序。谢谢! – lovefish 2016-06-06 13:44:38

2

在画布上使用图形的所有答案都不适用于GLSurfaceView。

要将GLSurfaceView的内容捕获到位图中,您应该考虑在Renderer::onDrawFrame()的内部实现gl.glReadPixels的自定义方法。

解决方案片段已发布here