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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With