2013-11-21 123 views
0

我目前正在將現有的iOS應用移植到Android的過程中,並遇到了需要在佈局中裁剪視圖內容的問題。Android剪輯/裁剪視圖內容

在iOS中,我只是簡單地訪問視圖層,然後相應地設置layer.contentsRect

在Android中,我想我已經找到了GLSurfaceView類的等效功能 - setClipBounds,但這僅適用於與API級別18的支持設備和拋出一個異常NoSuchMethodError在我的Galaxy S 3

不任何人都有一個替代解決方案(或支持庫)來裁剪或裁剪API級別9(2.3)的視圖內容?謝謝。

回答

0

這裏是我在xamarin(c#)中編寫的一些裁剪代碼,它是從Java移植過來的,您需要自行完成轉換,類名稱大致相同,方法和屬性暴露爲get /在Java中設置。

代碼作物位圖以一個圓,類似的Facebook浮動面:)

public static class BitmapHelpers 
{ 
    public static Bitmap LoadAndResizeBitmap (this string fileName, int width, int height) 
    { 
     // First we get the the dimensions of the file on disk 
     BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; 
     BitmapFactory.DecodeFile (fileName, options); 

     // Next we calculate the ratio that we need to resize the image by 
     // in order to fit the requested dimensions. 
     int outHeight = options.OutHeight; 
     int outWidth = options.OutWidth; 
     int inSampleSize = 1; 

     if (outHeight > height || outWidth > width) { 
      inSampleSize = outWidth > outHeight 
           ? outHeight/height 
           : outWidth/width; 
     } 

     // Now we will load the image and have BitmapFactory resize it for us. 
     options.InSampleSize = inSampleSize; 
     options.InJustDecodeBounds = false; 
     Bitmap resizedBitmap = BitmapFactory.DecodeFile (fileName, options); 

     return resizedBitmap; 
    } 

    public static Bitmap GetCroppedBitmap (Bitmap bitmap) 
    { 
     Bitmap output = Bitmap.CreateBitmap (bitmap.Width, 
            bitmap.Height, global::Android.Graphics.Bitmap.Config.Argb8888); 
     Canvas canvas = new Canvas (output); 

     int color = -1; 
     Paint paint = new Paint(); 
     Rect rect = new Rect (0, 0, bitmap.Width, bitmap.Height); 

     paint.AntiAlias = true; 
     canvas.DrawARGB (0, 0, 0, 0); 
     paint.Color = Color.White; 

     canvas.DrawCircle (bitmap.Width/2, bitmap.Height/2, 
      bitmap.Width/2, paint); 
     paint.SetXfermode (new PorterDuffXfermode (global::Android.Graphics.PorterDuff.Mode.SrcIn)); 
     canvas.DrawBitmap (bitmap, rect, rect, paint); 

     return output; 
    } 
}