当从资源加载Drawable
时,如何在绘制它时旋转它?例如,我想绘制一个箭头,并能够将其旋转以面向不同的方向。
你需要使用Bitmap和Canvas类的函数来准备可绘制对象:
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);
这段代码示例会在图像中心进行90度旋转。
本质上可以归纳为: 不要转换可绘制对象,而是进行(反向)画布变换
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();
//...
}
如果你有一个BitmapDrawable,可能希望通过设置抗锯齿来提高输出的质量。
drawable.setAntialias(true);
接受的答案对我无效。我的图片不是正方形的,所以我稍微修改了他的代码。
private Bitmap rotateDrawable(@DrawableRes int resId) {
Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), resId);
Bitmap bmpResult = Bitmap.createBitmap(bmpOriginal.getHeight(), bmpOriginal.getWidth(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(bmpResult);
int pivot = bmpOriginal.getHeight() / 2;
tempCanvas.rotate(90, pivot, pivot);
tempCanvas.drawBitmap(bmpOriginal, 0, 0, null);
return bmpResult;
}
mImageView.setImageBitmap(rotateDrawable(R.drawable.some_image));
ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);
Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);
源链接:
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation