Oleksandr Firsov
Oleksandr Firsov

Reputation: 1478

How to rotate line in Canvas

Currently I'm trying to rotate a line that I draw in canvas. I managed to do that, but as I rotate them 360° the line in previous position does not disappear, so in the end I don't get just 1 line, but whole circle.

Here's my code:

This snippet is initiated with the launch of the app

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;

imageView1 = (ImageView) findViewById(R.id.imageView1);
btn = (Button) findViewById(R.id.button1);

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
bmp = Bitmap.createBitmap(width, height, conf); // this creates a MUTABLE bitmap
canvas = new Canvas(bmp);
p = new Paint();
p.setColor(Color.RED);
imageView1.setImageBitmap(bmp);
p.setStrokeWidth(5);
canvas.drawLine(0, height/2, width, height/2, p);

And this piece - gets updated every sec.

canvas.rotate(refY, width/2, height/2);
canvas.drawLine(0, height/2, width, height/2, p);
btn.setText(Integer.toString(refY))

Upvotes: 1

Views: 1459

Answers (1)

tato.rodrigo
tato.rodrigo

Reputation: 2823

Save and restore the canvas accordingly:

canvas.save();
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); //clear everything drawn to the bitmap
canvas.rotate(refY, width/2, height/2);
canvas.drawLine(0, height/2, width, height/2, p);
canvas.restore();
btn.setText(Integer.toString(refY))

Upvotes: 6

Related Questions