Converting View to Bitmap
We need to have some variables initialized,
This is the Canvas we are going to draw in.
Canvas canvas = null
This is the layout we are going to use to create our view.
RelativeLayout relativeView ;
This is the background we are going to set in our view, we get it from a resource file (R.drawable.blackBgrnd). The BitmapFactory.decodeResource method is used to get a resource image and convert it in a Bitmap (we will use the Bitmap class). The object mContext (context) must be passed from the Activity we are working on.
Bitmap viewBgrnd = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.blackBgrnd);
We need another bitmap, to draw it on the canvas. We set the width and the height of this bitmap relative to the width and height we have created in our layout. Now this Bitmap is empty, but we are going to associate it with the canvas, so every time we draw in the canvas, it will be drawn in this bitmap object.
Bitmap returnedBitmap = Bitmap.createBitmap(relativeView .width, relativeView.height,Bitmap.Config.ARGB_8888);
First of all, we had the canvas = null, now we create a Canvas object using the auxiliary bitmap we had created before.
canvas = new Canvas(auxBitmap);
Now its time to create our view.
We can add Images, for example:
ImageView newImage = new ImageView(mContext);
We can set the imageView position in the view using “layout" method:
- l Left position, relative to parent
- t Top position, relative to parent
- r Right position, relative to parent
- b Bottom position, relative to parent
and finally adding it to our layout:
or we can add text:
TextView newText = new TextView(mContext);
newText.setText(“This is the text that its going to appear");
adding it to the layout in the same way:
Once we have added all elements we want to our layout, we have to create a paint object:
Paint paint = new Paint();
just to define default values of painting.
We use the “drawBitmap" method from the canvas:
canvas.drawBitmap(ViewBgrnd, 0, 0, paint);
and finally we call dispatchDraw in the layout to draw the children views (imageView, textView) in the canvas.
The returnedBitmap is the bitmap that contains the drawing of the views in the canvas, on it, we have the layout and its childrens as a Bitmap, after painting them in the Canvas.