【问题标题】:Android - Rotate a part of an ImageAndroid - 旋转图像的一部分
【发布时间】:2018-03-30 19:43:12
【问题描述】:

我基本上需要将ImageView 的一小部分旋转 90 度(例如):

在上图中,我想旋转 4 使其正确显示。只有 4 个,其余的应该保持垂直。

有什么方法可以实现吗?

通过实施 MikeM 建议的方法。我得到以下结果。

如您所见,我需要解决两个主要问题:

  1. 旋转的正方形正在工作,尽管处于拧紧位置。如何找到4 的确切坐标
  2. 图像的背景已更改为黑色。它曾经是透明的

【问题讨论】:

  • 是一张图片还是第四张是单独的图片?
  • 如果这只是一张图片,那么直接在上面绘制可能会更容易。
  • @chornge 不,这是一张图片。
  • 是的,我只是说你最初的想法。在我的脑海中,得到你的Bitmap,从那个数字中创建第二个Bitmap,使用Bitmap#createBitmap()方法之一,获取源Bitmap,旋转第二个Bitmap,然后使用Canvas 将其拉回第一个。其实也不算太牵扯,现在写出来了。我认为createBitmap() 方法之一甚至需要Matrix,因此您可以一步完成。不过,我必须稍后再检查。
  • 非常感谢,我会试试这个。也将其发布为答案,以便我可以投票

标签: android image-processing imageview


【解决方案1】:

如果您知道或可以计算出要旋转的区域的坐标和尺寸,那么该过程相对简单。

  1. 将图像加载为可变的Bitmap
  2. 从原来的所需区域创建第二个旋转Bitmap
  3. 在原始Bitmap 上创建Canvas
  4. 如有必要,清除剪裁区域。
  5. 将旋转区域重新绘制到原始区域。

在以下示例中,假设区域的坐标(xy)和尺寸(widthheight)已知。

// 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);

解决编辑中的问题:

  1. 原始示例中旋转区域的图形是基于长轴垂直的图像。 在修改该区域后,编辑中的图像已垂直旋转。

  2. 黑色背景是由于将生成的图像插入到MediaStore,它将图像保存为不支持透明度的JPEG格式。

【讨论】:

  • 再次感谢您提供的大力帮助。
猜你喜欢
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
相关资源
最近更新 更多