【问题标题】:Rotating a drawable in Android在 Android 中旋转可绘制对象
【发布时间】:2011-01-21 19:47:35
【问题描述】:

从资源加载的Drawable 在绘制时如何旋转?比如我想画一个箭头,画的时候可以旋转到不同的方向?

【问题讨论】:

标签: android graphics


【解决方案1】:

你需要使用Bitmap和Canvas Class函数来准备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 度旋转。

【讨论】:

  • 好的,如果您需要使图像半透明或需要缩放功能,您也可以查看stackoverflow.com/questions/4688306/…
  • 对我也很好。您遇到什么问题?
  • 正如 Jay 几年前所说,如果原始位图是方形的,这很好用,那么非方形位图呢?
  • 几年前我也问过:),你遇到了什么问题?
  • 另一种可能的旋转位图的方法,但无需在堆上创建临时位图(可能与原始位图一起占用大量空间),可以在这里找到:github.com/AndroidDeveloperLB/AndroidJniBitmapOperations跨度>
【解决方案2】:

基本上可以归结为:做一个(n 逆)画布变换而不是变换可绘制对象

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

【讨论】:

  • 我认为这是目前最有效的解决方案
  • 实际上 canvas.rotate() 已经完成之前绘制drawable。
  • 你不会错过onMeasure函数的实现吗?
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    基本上是这样的:

    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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多