Computerish Computerish - 6 months ago 19
Android Question

Rotating a drawable in Android

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?

Answer

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.

Comments