android how to rotate canvas rect

Mat Yus picture Mat Yus · Dec 9, 2012 · Viewed 17.5k times · Source

i create a rectangle in a specific size, and now i want rotate it to 45 degree, i used canvas.rotate, matrix, but not working. how is the proper way to rotate canvas in android? and i'm curios about Path.Direction.CW, is it used for rotation? but i don't see any rotation function in Path()

    paint.setAntiAlias(true);
    paint.setStrokeWidth(2);
    paint.setColor(Color.BLUE);
    paint.setAlpha(75);

    Path path = new Path();
    path.addRect(166, 748, 314, 890, Path.Direction.CW);
    canvas.rotate(45);
    canvas.drawPath(path, paint);

Answer

Alex North picture Alex North · Oct 29, 2013

To draw a rotated rectangle you need to rotate the canvas before drawing, (then rotate it back to right-side up if you're drawing anything else). Canvas.rotate() just alters the canvas's transformation matrix, which transforms shapes drawn after the call.

canvas.save();
canvas.rotate(45);
canvas.drawRect(166, 748, 314, 890, paint);
canvas.restore();

Path.Direction has nothing to do with rotation transforms. From the docs:

Specifies how closed shapes (e.g. rects, ovals) are oriented when they are added to a path.