10

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);
Mat Yus
  • 289
  • 1
  • 2
  • 14
  • If you're curious about Path.Direction, why not Google? First hit - http://developer.android.com/reference/android/graphics/Path.Direction.html. Why are you rotating the canvas before you draw the path? What are you trying to achieve? – Simon Dec 09 '12 at 11:22
  • it says clockwise and counterclockwise,i'm not understand its meaning. simple, i just want to rotate the rectangle i created "path.addRect(166, 748, 314, 890, Path.Direction.CW);". if i remove canvas.rotate(45), it will display a rectangle on screen, now i want to rotate it to 45 degree. already googled it but cannot find any solution – Mat Yus Dec 09 '12 at 11:40
  • You've rotated the canvas then you draw the path. So only whatever is drawn before the path (looks like nothing) is rotated. Why no draw path then rotate? – Simon Dec 09 '12 at 11:52
  • you mean like this? 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.drawPath(path, paint); canvas.rotate(45); its not working, same, nothing changes – Mat Yus Dec 09 '12 at 11:55

3 Answers3

18

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.

Alex North
  • 1,189
  • 13
  • 12
6

If you want to draw something from (x,y) point, you have to rotate the canvas around (x,y) point. For doing this you should use

canvas.rotate(45,x,y);

so,

canvas.save();
canvas.rotate(45,x,y);
//all drawing from (x,y) point
canvas.restore();
Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
2

Proper way should be something like this:

Path path = new Path();
path.addRect(166, 748, 314, 890, Path.Direction.CW);
canvas.save(); // first save the state of the canvas
canvas.rotate(45); // rotate it
canvas.drawPath(path, paint); // draw on it
canvas.restore(); // restore previous state (rotate it back)
croc
  • 1,416
  • 1
  • 18
  • 24