Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple canvases in a view

I have overridden the onDraw() method as follows:

public void onDraw(Canvas canvas1){
Canvas canvas2 = new Canvas();

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.graphic1);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.graphic2);

canvas1.drawBitmap(
          top,
          new Rect(0, 0, graphic1.getWidth(), graphic1.getHeight()),
          new Rect(0, 0, width, width),
          null);

canvas2.drawBitmap(
          top,
          new Rect(0, 0, graphic2.getWidth(), graphic2.getHeight()),
          new Rect(0, 0, width, width),
          null);

}

Only graphic1 on canvas1 gets displayed, canvas2 and graphic2 do not. How can i get multiple canvases to be displayed on a single view?

like image 403
Mark Manickaraj Avatar asked Feb 13 '26 10:02

Mark Manickaraj


1 Answers

As the comment said you're not attaching Canvas2 to anything. You're creating it each frame (which is bad), drawing to it and then letting it go our of scope to be garbage collected. What you should do it create Canvas2 with a backing Bitmap in the constructor of your view and keep it as a member. Then you can draw to it and then blit its Bitmap to Canvas1. For example:

public MyCustomView(Context context)
{
    super(context);
    _canvas2 = new Canvas(_backingBitmap);
}

public void onDraw(Canvas canvas1)
{
Bitmap graphic1 = BitmapFactory.decodeResource(getResources(), R.drawable.graphic1);
Bitmap graphic2 = BitmapFactory.decodeResource(getResources(), R.drawable.graphic2);

canvas1.drawBitmap(
          top,
          new Rect(0, 0, graphic1.getWidth(), graphic1.getHeight()),
          new Rect(0, 0, width, width),
          null);

_canvas2.drawBitmap(
          top,
          new Rect(0, 0, graphic2.getWidth(), graphic2.getHeight()),
          new Rect(0, 0, width, width),
          null);

canvas1.drawBitmap(
          top,
          new Rect(0, 0, _backingBitmap.getWidth(), _backingBitmap.getHeight()),
          new Rect(0, 0, width, width),
          null);
}
like image 195
CaseyB Avatar answered Feb 15 '26 23:02

CaseyB