2012-03-11 67 views
18

這是我的活動的一部分:Android。從中獲得的圖像尺寸是資源ID

private ImageView mImageView; 
private int resource; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    resource = getIntent().getIntExtra("res", -1); 

    Matrix initMatrix = new Matrix(); 

    mImageView = new ImageView(getApplicationContext()); 
    mImageView.setScaleType(ImageView.ScaleType.MATRIX); 
    mImageView.setImageMatrix(initMatrix); 
    mImageView.setBackgroundColor(0); 
    mImageView.setImageResource(resource); 
} 

我嘗試使用矩陣作爲規模類型(我想在以後添加多點觸控)的ImageView的範圍內顯示圖像。但在用戶開始交互之前,我希望圖像能夠居中放置在ImageView中。 我已經找到答案,關於如何解決它,但有一個問題對我來說: 使圖像居中使用矩陣我需要知道它的寬度和高度。有沒有什麼辦法在你擁有的時候獲得圖像大小是int資源

回答

40

使用BitmapFactory.decodeResource獲得資源的位圖對象,然後從位圖,你可以很容易地getHeightgetWidth

而且檢索圖像寬度/高度不要忘記recycle位圖

編輯:

這樣你將得到一個null位圖作爲輸出,但BitmapFactory.Options將設置與位圖的高度和。因此,在這種情況下,您不需要回收位圖

BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
dimensions.inJustDecodeBounds = true; 
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap, dimensions); 
int height = dimensions.outHeight; 
int width = dimensions.outWidth; 
+12

您還應該使用'BitmapFactory.Options尺寸=新BitmapFactory.Options(); dimensions.inJustDecodeBounds = true;'只是在不實際加載位圖到內存中的情況下解碼圖像尺寸。 – dmon 2012-03-11 15:13:16

+0

更好的一個,謝謝dmon – Blackbelt 2012-03-11 15:36:41

+0

對我來說,如果我設置inJustDecodeBounds = true,爲什麼mBitmap會變爲null?如果我將它設置爲false,它會返回一個位圖。 – Ankit 2013-06-21 08:04:15

11

對於任何沒有閱讀過dmon評論的人。做到這一點的代碼如下所示:

final Options opt = new BitmapFactory.Options(); 
opt.inJustDecodeBounds = true; 
BitmapFactory.decodeResource(getResources(), R.drawable.your_photo, opt); 

opt.outHeight; // height of resource 
opt.outWidth; // width of resource 
+1

你的意思是'BitmapFactory.decodeResource(getResources(),R.drawable.your_photo,opt);'? – Warpspace 2012-12-27 08:27:11

+0

當然可以。我會更新我的回答 – xbakesx 2012-12-27 13:02:42

+0

謝謝@xbakesx最佳解決方案! – 2015-04-26 18:47:58