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

别说谁变了你拦得住时间么 提交于 2019-12-13 04:39:37

问题


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:


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.



来源:https://stackoverflow.com/questions/10733883/issue-with-canvas-rotate-in-android-how-does-it-exactly-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!