0

当我对画布对象使用旋转方法时,画布对象不会旋转。为什么会这样?这是我的代码

package com.example.hello;

    import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout;

    public class CanvasDrawExample extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    setContentView(R.layout.example);
    LinearLayout rl=(LinearLayout)findViewById(R.id.rl);
     rl.addView(new CircleView(this));
    }
public class CircleView extends View
{

    public CircleView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub


    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub


        Paint p=new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setStrokeWidth(100);
        p.setStyle(Paint.Style.STROKE);
        p.setColor(Color.BLUE);

        canvas.drawRect(200, 100, 200, 100, p);
        canvas.save();  
        canvas.rotate((float)145);

        canvas.restore();
    }

}
}
4

2 回答 2

5

你保存你的画布,旋转它,然后在不做任何绘图的情况下恢复它。如果您尝试将 Rectangle 向右旋转 145º,请执行以下操作:

@Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub

        canvas.save();  
        canvas.rotate((float)-145,canvas.getWidth()/2,canvas.getHeight()/2);

        Paint p=new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setStrokeWidth(100);
        p.setStyle(Paint.Style.STROKE);
        p.setColor(Color.BLUE);

        canvas.drawRect(200, 100, 200, 100, p);


        canvas.restore();
    }

此外,不建议在 onDraw() 中实例化和定义 Paint。您应该在构造函数中声明和定义它,然后重用它。

于 2012-10-03T10:28:43.007 回答
0

为了使它起作用,您需要注释 canvas.restore();

于 2015-11-06T02:11:22.760 回答