canvas中的rotate()无效

时间:2012-10-03 10:22:39

标签: android android-animation android-canvas

当我将canvas方法与canvas对象一起使用时,canvas对象不会旋转。为什么会这样?这是我的代码

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();
    }

}
}

2 个答案:

答案 0 :(得分:5)

您保存画布,旋转它然后恢复它而不对其进行任何绘制。如果您尝试将矩形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。您应该在构造函数中声明并定义它,然后重用它。

答案 1 :(得分:0)

为了使其正常工作,您需要对canvas.restore();

进行注释