我正在使用以下代码来裁剪图像:
Bitmap raw = ((BitmapDrawable)hWlp).getBitmap();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager)
context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
wallpaper = Bitmap.createBitmap(raw, width/2, 0, width, height);
我的源图像(原始)是 800x960,目标图像是 800x480(屏幕尺寸)。所以我不明白为什么我会收到此错误:
java.lang.IllegalArgumentException: x + width must be <= bitmap.width()
如果在我的例子中 x + 宽度 (480/2 + 480) 是 720,而 bitmap.width() 是 960
你可以这样使用:
public static Bitmap cropAndScale (Bitmap source,int scale){
int factor = source.getHeight() <= source.getWidth() ? source.getHeight(): source.getWidth();
int longer = source.getHeight() >= source.getWidth() ? source.getHeight(): source.getWidth();
int x = source.getHeight() >= source.getWidth() ?0:(longer-factor)/2;
int y = source.getHeight() <= source.getWidth() ?0:(longer-factor)/2;
source = Bitmap.createBitmap(source, x, y, factor, factor);
source = Bitmap.createScaledBitmap(source, scale, scale, false);
return source;
}
这是示例,您可以通过显示度量更改变量
仅当你的应用处于横向时,你才会收到此错误;)我认为,在这种情况下,metrics.widthPixels可以返回800px而不是480px。