2017-10-18 67 views
1

我基本上需要旋轉90個degres一個ImageView的一小部分(例如)的一部分:的Android - 旋轉圖像

example

在上面的圖片,我想旋轉4所以它顯示正確。只有4個,其餘的應該保持垂直。

有沒有辦法實現它?

通過實施MikeM建議的方法。我收到以下結果。

result

正如你可以看到有兩個主要的事情,我需要解決:

  1. 旋轉後的廣場工作,雖然在擰位置。如何找出4的準確座標
  2. 圖像的背景已被更改爲黑色。它曾經是透明
+0

這是全部圖像還是4個獨立的圖像? – chornge

+0

如果這只是一個單一的圖像,它可能會更容易畫出來。 –

+0

@chornge不,它是一個圖像。 – Daniele

回答

2

如果您知道,或者自己看着辦,你想要的座標和區域的尺寸,旋轉,那麼這個過程是相對簡單的。

  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格式保存圖像。

+1

再次感謝您提供的巨大幫助。 – Daniele