我正在使用此代码裁剪图片:
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
答案 0 :(得分:0)
您可以这样使用:
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;
}
这是示例,您可以通过displaymetrics
更改变量答案 1 :(得分:0)
如果您的应用处于横向,您只能收到此错误;) 我认为,在这种情况下,metrics.widthPixels可以返回800px而不是480px。