2013-11-21 55 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; 
    } 
}