Dinesh Venkata
Dinesh Venkata

Reputation: 1087

rotate() in canvas has no effect

When I use the rotate method with my canvas object, the canvas object doesn't rotate. Why is this happening? Here is my code

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

}
}

Upvotes: 0

Views: 3139

Answers (2)

donmj
donmj

Reputation: 409

In order this to work you need to comment the canvas.restore();

Upvotes: 0

Benoît Bouré
Benoît Bouré

Reputation: 1037

You save your canvas, rotate it and then restore it without doing any drawing on it. If you are trying to rotate the Rectangle 145º to the right, do the following:

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

Also, it is not recommended to instantiate and define a Paint inside onDraw(). You should declare and define it in the constructor and then, reuse it.

Upvotes: 5

Related Questions