如何從左側和右側剪切矩形圖像(600 x 300)以適應方形ImageView?我不想調整圖片大小,我只是想裁剪,是300×300將圖像裁剪爲正方形 - Android
[解決方法]
正如@blackbelt說
Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
是偉大的裁剪圖像。那麼如何自動裁剪不同尺寸的圖像。我創建這個簡單的代碼爲:
// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
// From URL
Bitmap src = null;
try {
String URL = "http://www.example.com/image.jpg";
InputStream in = new java.net.URL(URL).openStream();
src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height)/2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);
ImageView.setImageBitmap(cropImg);
這正是我一直在尋找,獲得完美的圓形圖像,而不是橢圓形。但是,如果圖像的高度大於寬度,則不會在中心裁剪,因爲在createBitmap方法中y參數的值爲0。這是如何解決的:添加這兩行:'int cropH =(height - width)/ 2; \t cropH =(cropH <0)? 0:cropH;'使用cropH作爲y值。 \t'位圖cropImg = Bitmap.createBitmap(位圖,cropW,cropH,newWidth,newHeight);' – 2015-03-14 14:12:52
不錯,我看到你的觀點....基本上要對寬度和高度進行相同的計算。 – 2015-04-18 20:49:22