在Android上将视图转换为位图

我需要将视图转换为位图来预览我的视图并将其保存为图像。 我尝试使用下面的代码,但它创build一个空白图像。 我不明白我犯了什么错误。

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) { // } } 

这里是我的解决scheme:

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

请享用 :)

最投票的解决scheme不适合我,因为我的观点是一个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; } 

在canvas上使用绘图的所有答案都不适用于GLSurfaceView。

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

解决scheme片段已发布在这里 。