[英]Android - Rotate a part of an Image
如果您知道或可以算出您想旋转的区域的坐标和尺寸,则该过程相对简单。
Bitmap
。 Bitmap
。 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格式,不支持透明性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.