Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a drawable in Android

Tags:

How can a Drawable loaded from a resource be rotated when it is drawn? For example, I would like to draw an arrow and be able to rotate it to face in different directions when it is drawn?

like image 374
Computerish Avatar asked Jan 21 '11 19:01

Computerish


2 Answers

You need to use Bitmap and Canvas Class functions to prepare drawable:

Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.image2);
Bitmap bmResult = Bitmap.createBitmap(bmpOriginal.getWidth(), bmpOriginal.getHeight(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(bmResult); 
tempCanvas.rotate(90, bmpOriginal.getWidth()/2, bmpOriginal.getHeight()/2);
tempCanvas.drawBitmap(bmpOriginal, 0, 0, null);

mImageView.setImageBitmap(bmResult);

In this code sample rotation for 90 degrees over image center occurs.

like image 149
Zelimir Avatar answered Sep 21 '22 09:09

Zelimir


essentially it can be boiled down to: do a(n inverse) canvas transformation instead of transforming drawable

private BitmapDrawable drawable; // or Drawable

protected void onDraw(Canvas canvas) { // inherited from View 
  //...
  canvas.save();
  canvas.rotate(degrees, pivotX, pivotY);
  drawable.draw(canvas);
  canvas.restore();
  //...
}

if you have BitmapDrawable it may be desirable to increase quality of the output by setting antialiasing

drawable.setAntialias(true);
like image 23
jJ' Avatar answered Sep 22 '22 09:09

jJ'