Search code examples
androidcanvasrectangles

Android Rotating Rectangle and understanding the Canvas


I'm looking at making something that looks like the following:

Image I want

Which is basically a rectangle shape on the top left thats been rotated, and then two underneath it, tiled like it is. I've had a go at doing it but just can't get it done, basically I use:

int x = getWidth();
int y = getHeight();
canvas.save();
canvas.rotate(-45);
canvas.drawRect(x/2, y/2, x/2+100, y/2+40, paint);
canvas.restore();

And I've noticed that what should be a rectangle rotated near the centre of the screen is instead one that is to the top right of the screen. When I try doing something similar to (0,0, 100,100) I don't get any rectangle at all.

I guess I'm confused whether the coordinate system changes when the rotation of the canvas is done, and what would be the easiest way in looking into getting the image above on android (besides just creating it in photoshop and adding the png).


Solution

  • The single argument rotate(angle) will use 0,0 as the pivot point.

    If you want to rotate about your object, you should calculate some point on it to rotate about and use the 3 argument rotate(angle, pivotX, pivotY), ie:

    int x = getWidth();
    int y = getHeight();
    canvas.save();
    canvas.rotate(-45, x / 2, y / 2);
    canvas.drawRect(x / 2, y / 2, x / 2 + 100, y / 2 + 40, paint);
    canvas.restore();
    

    I made your design just for fun:

    int x = getWidth();
    canvas.rotate(-45);
    canvas.drawRect(-x, 0, x, h, green);
    canvas.drawRect(-x, h, 0, 2 * h, purple);
    canvas.drawRect(0, h, x, 2 * h, blue);
    

    Where h is the height of the rectangle.