Android裁剪中心位圖我有正方形或矩形的位圖。我采取最短的一面,做這樣的事情:int value = 0;if (bitmap.getHeight() <= bitmap.getWidth()) {
value = bitmap.getHeight();} else {
value = bitmap.getWidth();}Bitmap finalBitmap = null;finalBitmap = Bitmap.createBitmap(bitmap, 0, 0, value, value);然后我使用它將它縮放到144 x 144位圖:Bitmap lastBitmap = null;lastBitmap = Bitmap.createScaledBitmap(finalBitmap, 144, 144, true);問題是它裁剪原始位圖的左上角,任何人都有代碼來裁剪位圖的中心?
3 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
這可以通過以下方法實現: Bitmap.createBitmap(source,x,y,width,height)
if (srcBmp.getWidth() >= srcBmp.getHeight()){ dstBmp = Bitmap.createBitmap( srcBmp, srcBmp.getWidth()/2 - srcBmp.getHeight()/2, 0, srcBmp.getHeight(), srcBmp.getHeight() );}else{ dstBmp = Bitmap.createBitmap( srcBmp, 0, srcBmp.getHeight()/2 - srcBmp.getWidth()/2, srcBmp.getWidth(), srcBmp.getWidth() );}

慕村9548890
TA貢獻1884條經驗 獲得超4個贊
雖然上面的大多數答案提供了一種方法來實現這一點,但已經有一種內置的方法來實現這一點,它是一行代碼(ThumbnailUtils.extractThumbnail()
)
int dimension = getSquareCropDimensionForBitmap(bitmap);bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);...//I added this method because people keep asking how //to calculate the dimensions of the bitmap...see comments belowpublic int getSquareCropDimensionForBitmap(Bitmap bitmap){ //use the smallest dimension of the image to crop to return Math.min(bitmap.getWidth(), bitmap.getHeight());}
如果您希望回收位圖對象,可以傳遞使其成為的選項:
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
public static Bitmap extractThumbnail(Bitmap source,int width,int height)
在API級別8中添加創建所需大小的居中位圖。
參數source原始位圖源寬度目標寬度高度目標高度
在使用接受的答案時,我有時會出現內存錯誤,并且使用ThumbnailUtils為我解決了這些問題。此外,這更清潔,更可重復使用。
- 3 回答
- 0 關注
- 497 瀏覽
添加回答
舉報
0/150
提交
取消