从imageview中心点旋转图像

Ind*_*Boy 2 android android-imageview

我想在android中旋转图像.我发现这个有用的帖子,它的效果很好,但似乎在android中的旋转从左下角开始.我需要从中心点旋转图像.可能吗?代码相同是有帮助的.谢谢.

new*_*yca 7

@ goodm解决方案的问题是imageView可能还没有布局,导致imageView.getDrawable().getBounds().width()和.height()返回0.这就是为什么你仍然在0左右旋转, 0.解决此问题的一种方法是确保在布局后使用以下内容创建和应用矩阵:如何在Android中为布局设置固定宽高比

@Voicu的解决方案没问题,但它需要你直接使用效率低下的位图.更好的方法是直接查询图像资源的大小,但实际上并没有将其加载到内存中.我使用实用方法来做到这一点,它看起来像这样:

public static android.graphics.BitmapFactory.Options getSize(Context c, int resId){
    android.graphics.BitmapFactory.Options o = new android.graphics.BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(c.getResources(), resId, o);
    return o;
}
Run Code Online (Sandbox Code Playgroud)

这将返回一个包含实际宽度和高度的Options对象.从活动中你可以像这样使用它:

ImageView img = (ImageView)findViewById(R.id.yourImageViewId);
Options o = getSize(this, R.drawable.yourImage);
Matrix m = new Matrix();
m.postRotate(angle, o.outWidth/2, o.outHeight/2);
img.setScaleType(ScaleType.MATRIX);
img.setImageMatrix(m);
Run Code Online (Sandbox Code Playgroud)