在Android中旋转drawable

时间:2011-01-21 19:47:36

标签: android graphics

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

4 个答案:

答案 0 :(得分:20)

您需要使用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);

在此代码示例中,将在图像中心上旋转90度。

答案 1 :(得分:10)

基本上它可以归结为:做一个(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();
  //...
}

如果你有BitmapDrawable,可能需要通过设置抗锯齿来提高输出质量

drawable.setAntialias(true);

答案 2 :(得分:2)

接受的答案对我不起作用。我有非正方形图像,所以我改变了他的代码。

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

答案 3 :(得分:0)

基本上是这样的:

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