2012-10-11 108 views

回答

4

使用此代碼

int width = bitmapOrg.width(); 
int height = bitmapOrg.height(); 
int newWidth = 200; 
int newHeight = 200; 

// calculate the scale - in this case = 0.4f 
float scaleWidth = ((float) newWidth)/width; 
float scaleHeight = ((float) newHeight)/height; 

// createa matrix for the manipulation 
Matrix matrix = new Matrix(); 
// resize the bit map 
matrix.postScale(scaleWidth, scaleHeight); 

// recreate the new Bitmap 
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
        width, height, matrix, true); 

// make a Drawable from Bitmap to allow to set the BitMap 
// to the ImageView, ImageButton or what ever 
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); 

ImageView imageView = new ImageView(this); 

// set the Drawable on the ImageView 
imageView.setImageDrawable(bmd); 
+0

如何設置newWidth等於設備寬度,以便根據設備屏幕寬度縮放圖像? – rohit

+0

int newWidth = getWindowManager()。getDefaultDisplay()。getWidth(); – Deepika

+0

btw一個問題 - 它是拉伸圖像我不想拉伸圖像,我想剪切圖像的一部分,如我在示例中所示..更常見我想裁剪它:) – rohit

6
// Set some constants 
private static final Bitmap SOURCE_BITMAP = BitmapFactory.decodeFile(....); // Get the source Bitmap using your favorite method :-) 
private static final int START_X = 10; 
private static final int START_Y = 15; 
private static final int WIDTH_PX = 100; 
private static final int HEIGHT_PX = 100; 

// Crop bitmap 
Bitmap newBitmap = Bitmap.createBitmap(SOURCE_BITMAP, START_X, START_Y, WIDTH_PX, HEIGHT_PX, null, false); 

// Assign new bitmap to ImageView 
ImageView image = (ImageView)findViewById(R.id.image_view); 
image.setImageBitmap(newBitmap); 
+0

我試過這個,但我不能根據設備屏幕大小設置新的圖像寬度,請參閱deepika回答第1條評論 – rohit

+0

Display display =((WindowManager)getSystemService(Context.WINDOW_SERVICE))。getDefaultDisplay(); int screenWidth = display.getWidth(); –

0

如果有人尋求削減圖像從底部

// recreate the new Bitmap 
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, x, y, 
        width, height, matrix, true); 

替換以下PARAMS這個邏輯

Y:(bitmapOrg .getHeight() - 1) - (問題中存在的紅色框的高度)

高度:(存在於問題的紅色框的高度)

這樣你可以避免例外,如(對於x需要相應修改)

IllegalArgumentException: x + width must be <= bitmap.width() in android 

IllegalArgumentException: y + width must be <= bitmap.height() in android 
相關問題