我目前正在将现有的iOS应用移植到Android上,并遇到了需要在布局中裁剪视图内容的障碍。
在iOS中,我只是访问视图层,然后相应地设置layer.contentsRect
。
在Android中,我认为我找到了GLSurfaceView类的等效函数 - setClipBounds
,但这仅适用于支持API级别18的设备,并在我的Galaxy S上引发NoSuchMethodError
异常3。
是否有人有替代解决方案(或支持库)来剪裁或裁剪API级别9(2.3)的视图内容?感谢。
答案 0 :(得分:0)
这里是我在xamarin(c#)中编写的一些裁剪代码,它是从Java移植的,你需要自己进行转换,类名大致相同,方法和属性公开为get / set在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;
}
}