代码之家  ›  专栏  ›  技术社区  ›  Daniele

Android-旋转图像的一部分

  •  1
  • Daniele  · 技术社区  · 7 年前

    我基本上需要旋转90度 ImageView (例如):

    example

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

    有什么方法可以实现吗?

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

    result

    正如你们所见,我需要解决两件主要的事情:

    1. 旋转的正方形正在工作,尽管处于拧动位置。我该如何找到 4
    2. 图像的背景已更改为黑色。它过去是透明的
    1 回复  |  直到 7 年前
        1
  •  2
  •   Mike M.    7 年前

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

    1. 将图像作为可变对象加载 Bitmap .
    2. 位图 从原始图像中删除所需区域。
    3. 创建 Canvas 在原件上 位图
    4. 如有必要,清除剪裁区域。
    5. 将旋转区域绘制回原始区域。

    在下面的示例中,假设区域的坐标( 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);
    

    1. 原始示例中旋转区域的图形基于长轴垂直的图像。编辑中的图像已旋转到垂直方向 之后

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