如果您知道或能够计算出要旋转的区域的坐标和尺寸,那么这个过程相对简单。
-
将图像作为可变对象加载
Bitmap
.
-
位图
从原始图像中删除所需区域。
-
创建
Canvas
在原件上
位图
-
如有必要,清除剪裁区域。
-
将旋转区域绘制回原始区域。
在下面的示例中,假设区域的坐标(
x
,
y
)和尺寸(
width
,
height
)已经知道了。
// Options necessary to create a mutable Bitmap from the decode
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
// Load the Bitmap, here from a resource drawable
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resId, options);
// Create a Matrix for 90° counterclockwise rotation
Matrix matrix = new Matrix();
matrix.postRotate(-90);
// Create a rotated Bitmap from the desired region of the original
Bitmap region = Bitmap.createBitmap(bmp, x, y, width, height, matrix, false);
// Create our Canvas on the original Bitmap
Canvas canvas = new Canvas(bmp);
// Create a Paint to clear the clipped region to transparent
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// Clear the region
canvas.drawRect(x, y, x + width, y + height, paint);
// Draw the rotated Bitmap back to the original,
// concentric with the region's original coordinates
canvas.drawBitmap(region, x + width / 2f - height / 2f, y + height / 2f - width / 2f, null);
// Cleanup the secondary Bitmap
region.recycle();
// The resulting image is in bmp
imageView.setImageBitmap(bmp);
-
原始示例中旋转区域的图形基于长轴垂直的图像。编辑中的图像已旋转到垂直方向
之后
-
黑色背景是由于将生成的图像插入到
MediaStore
,它以JPEG格式保存图像,该格式不支持透明度。