简体   繁体   English

在Android中旋转drawable

[英]Rotating a drawable in Android

How can a Drawable loaded from a resource be rotated when it is drawn? 如何从资源中加载的DrawableDrawable时旋转? 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和Canvas类函数来准备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. 在此代码中,样本在图像中心上旋转90度。

essentially it can be boiled down to: do a(n inverse) canvas transformation instead of transforming drawable 本质上它可以归结为:做一个(n反)画布转换而不是转换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 如果你有BitmapDrawable,可能需要通过设置抗锯齿来提高输出质量

drawable.setAntialias(true);

Accepted answer doesn't work for me. 接受的答案对我不起作用。 I have non square image, so I changed his code a bit. 我有非方形图像,所以我改变了他的代码。

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));

essentially this: 基本上这个:

ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);
Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);

source link: 来源链接:

http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM