在Android中旋转drawable

Drawable如何从资源加载Drawable ? 例如,我想绘制一个箭头,并且能够在绘制时将它旋转到不同的方向?

您需要使用位图和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度。

本质上可以归结为:做一个(n反)的canvas转换,而不是转换可绘制的

 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