I'm working on a custom view (extends View
) and working in the onDraw
method.
I have made a path of an arrow:
ARROW_PATH = new Path();
ARROW_PATH.setLastPoint(20, 37);
ARROW_PATH.lineTo(14, 25);
ARROW_PATH.lineTo(18, 26);
ARROW_PATH.lineTo(17, 4);
ARROW_PATH.lineTo(23, 4);
ARROW_PATH.lineTo(22, 26);
ARROW_PATH.lineTo(26, 25);
ARROW_PATH.close();
In different scenarios it needs to be rotated to depict a certain angle, and I need to draw it at a particular coordinate in the view. The coordinate also changes depending on the scenario.
I've tried playing around with Canvas.rotate
however, it looks like the aspect of the path is skewed when the px
and py
values are not equal (the arrow gets narrower and taller when py > px
.
I have also tried Canvas.rotate(angle, 0, 0);
and then ARROW_PATH.moveTo(x, y);
开发者_开发知识库but it looks like the coords are rotated by the arbitrary angle making it very hard to calculate the required coordinate.
Ideally, I'd like to rotate the path and not the canvas but I don't think this operation is supported by the API.
Can someone suggest a better approach to this problem?
thanks, p.
This is a proper way to permanently rotate a path (it will stay like this until the next application of a matrix):
Matrix mMatrix = new Matrix();
RectF bounds = new RectF();
mPath.computeBounds(bounds, true);
mMatrix.postRotate(myAngle, bounds.centerX(), bounds.centerY());
mPath.transform(mMatrix);
I found a way of making it work.
Firstly I modified my Path
so that it was centered
ARROW_PATH = new Path();
ARROW_PATH.setLastPoint(0, 17);
ARROW_PATH.lineTo(-6, 5);
ARROW_PATH.lineTo(-2, 6);
ARROW_PATH.lineTo(-3, -16);
ARROW_PATH.lineTo(3, -16);
ARROW_PATH.lineTo(2, 6);
ARROW_PATH.lineTo(6, 5);
ARROW_PATH.close();
and then an extra call to translate helps locate the drawing:
canvas.save();
canvas.rotate(angle, x, y);
canvas.save();
canvas.translate(x, y);
canvas.drawPath(ARROW_PATH, paint);
canvas.restore();
canvas.restore();
精彩评论