Issue with Canvas.rotate() in Android .How does it

2019-08-25 01:12发布

Please find the code of my onDraw method below(.I'm trying to rotate the canvas(//Rotate call -b) by 25 degrees after drawing the arc .But i find that the arc is still drawn from 0 to 50 degrees.I was expecting it to move by another 25 degrees.

public class CustomView extends View {

    public CustomView(Context context) {
        super(context);

    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }
    protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            Paint paint = new Paint();
            paint.setColor(Color.RED);
            int px = getMeasuredWidth() / 2;
            int py = getMeasuredHeight() / 2;

            // radius - min 
            int radius = 130;

            // Defining bounds for the oval for the arc to be drawn
            int left = px - radius;
            int top = py - radius;
            int right = left + (radius * 2);
            int bottom = top + (radius * 2);

            RectF rectF = new RectF(left, top, right, bottom);
            paint.setColor(Color.RED);
            paint.setStyle(Style.FILL);

                //canvas.rotate(25,px,py);//Rotate call -a

        canvas.drawArc(rectF, 0, 50, true, paint);

            canvas.rotate(25,px,py);//Rotate call  -b

        }
}

But if i place the rotate call(//Rotate call -a) before drawing the arc i see that the arc drawn is shifted by 25 degrees more .What exactly is happening here? Can someone explain to me?

Thanks

1条回答
欢心
2楼-- · 2019-08-25 02:14

The Canvas maintains a Matrix that is responsible for all transformations on it. Even for rotation. As you can see in the documentation, the rotate method says:

Preconcat the current matrix with the specified rotation.

All transformations are done on the Canvas Matrix,hence, on the Canvas. The arc you draw isn't rotated. You first rotate the Canvas and then draw on it.

Hence, in your code, call -a works, not call -b.

EDIT: For issues like postrotate and prerotate check the Matrix class(postRotate and preRotate methods).

Few Examples: this and this.

And few things you might want to read : this and this.

查看更多
登录 后发表回答