【问题标题】:Android: Rotation of image around the centerAndroid:围绕中心旋转图像
【发布时间】:2011-07-08 03:49:59
【问题描述】:

我正在尝试围绕中心旋转图像。这通常使用 RotateAnimation 工作,但我希望它更快一点。我现在将 SurfaceView 模式与单独的绘图线程一起使用。

这是正确绘制位图的代码(取决于外部“标题”)

航向 = 以度为单位的角度, 位图 = 位图, w = 位图的宽度, h = 位图的高度。

    Matrix m = new Matrix();
    m.preRotate(heading, w/2, h/2);
    m.setTranslate(50,50);

    canvas.drawBitmap(bitmap, m, null);

缺点:图像是一个圆形,上面的代码会产生可见的锯齿效果...

下面的代码也在旋转图像,但在旋转时(比如顺时针从 0 度到 45 度),新图像的中心会向下/向右移动。我想,偏心效果是由于新图像的扩大宽度/高度?但是,如果设置了 filter=true,则此代码不会产生别名。有没有办法使用代码 #1 但有抗锯齿或使用代码 #2 但摆脱中心移动?

    Matrix m = new Matrix();
    m.preRotate(heading, w/2, h/2);
    m.setTranslate(50,50);

    Bitmap rbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);
    canvas.drawBitmap(rbmp, 50, 50, null);

更新:根据该线程中的讨论,代码 #2 的正确版本(抗锯齿 正确旋转)看起来像这样(省略了 50,50 的偏移量):

        Matrix m = new Matrix();

        m.setRotate(heading, w/2, h/2);
        Bitmap rbpm = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);
        canvas.drawBitmap(rbpm, (w - rbpm.getWidth())/2, (h - rbpm.getHeight())/2, null);

谢谢。

【问题讨论】:

  • 上面代码中setTranslate的作用是什么?我不记得为了简单的旋转而这样做。
  • 嗯。是的,这可以放弃...谢谢。已更正。
  • 哦,对不起。还原了我的更改。 setTranslate 是将结果偏移到 (50,50) 所必需的。

标签: android image rotation


【解决方案1】:

找到原始图像的中心,并使用它找到新图像和中心:

Matrix minMatrix = new Matrix();
//height and width are set earlier.
Bitmap minBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas minCanvas = new Canvas(minBitmap);

int minwidth = bitmapMin.getWidth();  
int minheight = bitmapMin.getHeight();
int centrex = minwidth/2;
int centrey = minheight/2;

minMatrix.setRotate(mindegrees, centrex, centrey);
Bitmap newmin = Bitmap.createBitmap(minBitmap, 0, 0, (int) minwidth, (int) minheight, minMatrix, true);

minCanvas.drawBitmap(newmin, (centrex - newmin.getWidth()/2), (centrey - newmin.getHeight()/2), null);
minCanvas.setBitmap(minBitmap);

【讨论】:

  • 好的,minCanvas2 是什么? bitmapMin 是初始位图吗?另外 - minBitmap2 未声明。请详细说明。
  • 不知何故,您的代码没有任何意义 - 至少作为 sn-p :(
  • 好的。最后:翻译到我的命名空间中,您的答案将如下所示。这就是解决方案:抗锯齿正确旋转。
  • 对不起。我应该让我的代码与您的应用程序更相关,甚至尝试使其与您的命名空间相匹配。我也没有说明新画布是在哪里创建的,也没有说明原因。如果我有时间,我会尝试更新它。无论如何,我很高兴它有所帮助。
  • 是的,非常感谢。您的提示为我指明了正确的方向 :) 但不幸的是,整个事情的表现并不好 :( 我正在准备一篇新帖子,并进行一些测量,之后会在此处放置一个链接。你介意有吗也看看这个?提前致谢。
猜你喜欢
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多