旋转位图偏离中心

时间:2014-06-17 00:40:41

标签: android bitmap rotation

我旋转图像然后在ImageView中显示它,问题是它旋转后,它会向上和向右移动。

我的旋转代码,在使用此方法旋转后,它已保存到文件系统中:

private Bitmap rotateImage( Bitmap original, int degrees )
{
        final int height = original.getHeight(), width = original.getWidth();

        Matrix matrix = new Matrix();
        matrix.setRotate( degrees, width / 2, height / 2 );
        RectF rectF = new RectF( 0, 0, width, height );
        matrix.mapRect( rectF );
        Bitmap rotatedImage = Bitmap.createBitmap( (int)rectF.width(), (int)rectF.height(), original.getConfig() );
        Canvas canvas = new Canvas( rotatedImage );
        canvas.drawBitmap( original, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ) );

        return rotatedImage;
}

我的代码从文件系统加载已保存的图像:

private Bitmap loadImage( String imagePath, int maxHeight, int maxWidth )
{
BitmapFactory.Options fOptions = new BitmapFactory.Options();
int fHeight, fWidth, scale;

fOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile( imagePath, fOptions );
fHeight = fOptions.outHeight;
fWidth = fOptions.outWidth;
scale = Math.max( maxHeight > 0 ? fHeight / maxHeight : 0,
                      maxWidth > 0 ? fWidth / maxWidth : 0 );

fOptions.inJustDecodeBounds = false;
fOptions.inSampleSize = scale;
fOptions.inPurgeable = true;

return BitmapFactory.decodeFile( imagePath, fOptions );
}

ImageView xml:

<ImageView android:id="@+id/image"
           android:layout_height="wrap_content"
           android:layout_margin="10dp"
           android:layout_width="match_parent"
           android:scaleType="centerCrop" />

图像旋转得很好,但是当它显示时,它会从它应该的位置向右和向上偏移,然后由ImageView裁剪掉。任何人都可以看到导致它被抵消的原因吗?

2 个答案:

答案 0 :(得分:2)

问题是您的枢轴是根据原始图像尺寸计算的,原始图像尺寸可能不是最终图像的中心。

在绘制图像之前,我会像这样设置矩阵:

//center the source image
matrix.setTranslate(-width/2, -height/2);
//rotate the image
matrix.postRotate(degrees);
//now move it to the center of your final image
matrix.postTranslate(rotatedImage.getWidth()/2, rotatedImage.getHeight()/2);

//now draw the image
canvas.drawBitmap( original, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ) );

答案 1 :(得分:0)

这是因为图像相对于左上角旋转。旋转图像后,将其移至width/2height/2