Search code examples
javaandroidcanvasrectangles

Drawing bunch of rotated rectangles on android canvas


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.


Solution

  • 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.