Android:围绕中心旋转图像

4
我正在尝试绕中心旋转图像。使用RotateAnimation通常可以实现这一点,但我希望它更快一些。现在我正在使用SurfaceView模式和单独的绘制线程。
以下是正确绘制位图的代码(取决于外部“heading”):
heading = 角度, bitmap = 位图, 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的目的是什么?我不记得在简单旋转时这样做过。 - Kevin
嗯,可以删除这个...谢谢。已经更正了。 - decades
哦,抱歉。我撤销了我的更改。setTranslate是必要的,以将结果偏移为(50,50)。 - decades
1个回答

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未声明。请详细说明。 - decades
你的代码有点不太合理 - 至少作为片段来看不是很清晰 :( - decades
好的。最终结果是:翻译到我的命名空间中,你的答案看起来像这样。这就是解决方案:抗锯齿和正确旋转。 - decades
抱歉。我应该让我的代码更符合你的应用程序,甚至尝试使其匹配你的命名空间。我也没有展示新画布是在哪里创建的以及为什么要创建它。如果我有时间,我会尝试更新它。不管怎样,我很高兴它能帮到你。 - Unconn
是的,非常感谢。你的提示指引了我正确的方向 :) 但不幸的是整个事情表现得并不好 :( 我正在准备一篇新文章,附带一些测量数据,并在此后放置一个链接。您介意也看一下吗?提前致谢。 - decades
这是链接:http://stackoverflow.com/questions/5186212/android-canvas-drawbitmap-performance-issue - decades

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接