簡體   English   中英

如何在Android中獲取ImageView / Bitmap的高度和寬度

[英]How to get the height and width of an ImageView/Bitmap in Android

我想獲得ImageView或背景圖像中的圖像位圖的高度和寬度。 請幫助我,任何幫助將不勝感激。

您可以通過使用getWidth()和getHeight()來獲取ImageView的高度和寬度,而這不會為您提供圖像的精確寬度和高度,為了獲得圖像寬度高度,首先需要將drawable作為背景然后轉換可繪制到BitmapDrawable以將圖像作為Bitmap從中獲取寬度和高度,就像這里一樣

Bitmap b = ((BitmapDrawable)imageView.getBackground()).getBitmap();
int w = b.getWidth();
int h = b.getHeight();

還是喜歡這里

imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
int w = b.getWidth();
int h = b.getHeight();

上面的代碼將為您提供當前imageview大小的位圖,如設備的屏幕截圖

僅適用於ImageView大小

imageView.getWidth(); 
imageView.getHeight(); 

如果你有可繪制的圖像,並且你想要這個尺寸,你就可以這樣做

Drawable d = getResources().getDrawable(R.drawable.yourimage);
int h = d.getIntrinsicHeight(); 
int w = d.getIntrinsicWidth();      

由於某些原因,接受的答案對我不起作用,而是按照目標屏幕dpi實現了圖像尺寸。

方法1

Context context = this; //If you are using a view, you'd have to use getContext();
Resources resources = this.getResources();
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, R.drawable.cake, bounds); //use your resource file name here.
Log.d("MainActivity", "Image Width: " + bounds.outWidth);

這是原始鏈接

http://upshots.org/android/android-get-dimensions-of-image-resource

方法2

BitmapDrawable b = (BitmapDrawable)this.getResources().getDrawable(R.drawable.cake);
Log.d("MainActivity", "Image Width: " + b.getBitmap().getWidth());

它沒有顯示圖像資源中的確切像素數,而是一個有意義的數字,也許有人可以進一步解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM