如何在Android中围绕图像中心旋转位图而不会发生振荡运动 [英] How to rotate a bitmap in Android about images center smoothly without oscillatory movement

查看:106
本文介绍了如何在Android中围绕图像中心旋转位图而不会发生振荡运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于用户点击10度旋转位图图像。在众多stackoverflow和谷歌答案之后,我尝试了Matrix旋转的各种组合。

I want to rotate a bitmap image based on user click by 10 deg. Following numerous stackoverflow and google answers, I tried various combinations of Matrix rotation.

然而,图像并没有像预期的那样真正旋转,并且给出了旋转+振荡的抖动视图帆布中心。为了测试,每次调用对象的绘制方法时,我都会将旋转角度增加10度(而不是点击次数)。图像是一个对称的圆圈[64x64包围矩形]我希望它在屏幕中心围绕它自己的中心像一个轮子一样旋转,但它会旋转并沿着对角线向右下方移动并以振荡的方式向后移动到屏幕中心。

However the image doesn't really rotate as expected and gives a jittery view of rotation + oscillation about canvas center. To test I am increasing rotation angle by 10 deg (instead of clicks) each time object's draw method is called. The image is a symmetrical circle [64x64 enclosing rectangle] and I expect it to rotate at center of screen about it's own center like a wheel, but it rotates and moves diagonally towards right-down and moves back upto center of screen in an oscillatory fashion.

 public void draw(Canvas canvas) {
    Matrix matrix = new Matrix();

    rotation += 10;
    float px = this.viewWidth/2;
    float py = this.viewHeight/2;
    matrix.setRotate(rotation, bitmap.getWidth()/2, bitmap.getHeight()/2);
    Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, getImgWidth(), getImgHeight(), matrix, true);
    canvas.drawBitmap(newbmp, px - (getImgWidth()/2), py - (getImgHeight()/2), null);

 }


推荐答案

这是一个例子。
我把它分成3步。
第一个翻译移动位图,使其中心位于0,0
然后旋转
,最后将位图中心移动到画布上你想要的位置。
您不需要第二个位图。

Here is an example. I broke it to 3 steps. The first translate moves the bitmap so that it's center is at 0,0 Then a rotation, and finally move the bitmap center to where you want it on the canvas. You don't need the second bitmap.

Matrix matrix = new Matrix();
rotation += 10;
float px = this.viewWidth/2;
float py = this.viewHeight/2;
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotation);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, null);

作为优化,在此方法之外创建一次Matrix,并通过调用<$替换创建c $ c> matrix.reset()

As an optimization, create the Matrix once outside this method and replace the creation with a call to matrix.reset()

这篇关于如何在Android中围绕图像中心旋转位图而不会发生振荡运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆