4
votes

I have a task to draw many rectangles on canvas, but all of them have a rotation angle by which they have to be rotated on canvas. Many of suggestions I ran into while searching for solution of this problem indicated the way to draw a rectangle and rotate the canvas (Canvas.rotate(angle)), but it rotates all canvas and is only possible with one rectangle. What could be the best way to draw many of rotated rectangles on canvas? I want to draw rectangles (single color, with Paint), but not bitmaps, due to time efficiency and memory.

The primary way I would do currently is creating a load of canvases and drawing one rectangle on each of them and rotating canvases considering the angle of rectangles. I think that it is not a smart way due to many canvases and for each of them I should create a separate SurfaceHolder and it is a mess...

Note that for each rectangle I have coordinates of all of its 4 corners, its width, height, center, angle.

1
either save() your canvas, rotate() it, draw your rect and finally restore() the canvas or draw a rotated Path object holding your rect by calling Canvas#drawPath but i think that the first option would be fasterpskink
Thank you, pskink, for both of these suggestions. I have implemented the first one in my program and it worked.Dainius Šaltenis

1 Answers

6
votes

You can rotate the canvas for drawing each rectangle, and then restore the original orientation after. Then set the new rotation for the next rectangle, draw, store, and repeat.

Approximately this:

  //Save and rotate canvas 
  canvas.save();
  canvas.rotate(angle, pivotX, pivotY);

  canvas.drawRect(...);

  //restore canvas
  canvas.restore();

  // rotate and draw the second rectangle
  canvas.rotate(angle, pivotX, pivotY);

  canvas.drawRect(...);

  canvas.restore();

  // repeat as necessary

where 'angle' is different for each rectangle.