Question

I have a canvas:

Canvas c=null;

and a loop that draws a rect, because I change the position of the rect every loop, the rect will move on the screen.

int i=0;
while(isRunning){
   i++;
   c=null;
   Paint p=new Paint();
   p.setColor(Color.BLACK);
   c.drawRect(i,i,i+5,i+5,p);
}

I want to create a backgorund, for this example(a big blue rect over all screen):

   Paint backgroundP=new Paint();
   backgroundP.setColor(Color.BLUE);
   c.DrawRect(view.getLeft(),view.getTop(),view.getRight().view.getBottom(),backgroundP);

the background is created before the loop(before i create the rect that moves).

now what i want to do is to save the canvas with the background(the big blue rect) on a bitmap, and then in the loop to draw the small rect that moves over the bitmap-so it will draw the rect,which will move and it will draw the background (so there will be the rect that moves and a background)

How do I save a canvas on a bitmap and then draw that bitmap on the canvas that in the loop?

if you don't mind, posting a code that does what I described in the example.

Was it helpful?

Solution

If you simply want to draw a rect on a plain-colored background you could try this:

private Paint rectPaint = new Paint();
private Rect rect = new Rect(0, 0, 5, 5);

protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLUE);
    canvas.drawRect(rect, rectPaint);
}

This code does not move your rect yet. You could use the following method to add an offset to the previously defined rect, thus moving it on the canvas.

public void moveRect(int dx,int dy){
    rect.offset(dx, dy);
}

Where exactly this should happen depends on the rest of your code. (Maybe each time onDraw() is called?)

If your aim is to draw different bitmaps on a canvas you should try this method

canvas.drawBitmap(bitmap, left, top, paint);

For this you can either load the bitmap from a resource:

Bitmap backgroundBitmap = BitmapFactory.decodeResource(context,
            R.drawable.your_background_bitmap);

or initialize an empty Bitmap and draw to this bitmap using a Canvas:

Bitmap backgroundBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
            Config.ARGB_8888);
Canvas backgroundCanvas = new Canvas(backgroundBitmap);
backgroundCanvas.drawColor(Color.BLUE);

If you have more information on what your code is about (e.g. a custom View, a game loop) I could help you with more precise answers.

OTHER TIPS

You don't save the canvas to a bitmap, you make the canvas write to a bitmap from the beginning.

Canvas canvas = new Canvas(bitmap);

That will make the canvas write to an in memory bitmap. Then just use that canvas to draw on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top