如何在Android中获取ImageView / Bitmap的高度和宽度

时间:2012-01-16 12:59:47

标签: android imageview android-bitmap dimensions

我想获得ImageView或背景图像中图像位图的高度和宽度。请帮助我,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:80)

您可以通过使用getWidth()和getHeight()来获取ImageView的高度和宽度,而这不会为您提供图像的精确宽度和高度,因为首先获取图像宽度高度需要将drawable作为然后将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();      

答案 1 :(得分:1)

由于某些原因,接受的答案对我不起作用,而是根据目标屏幕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());

它没有显示图像资源中的确切像素数,而是一个有意义的数字,也许有人可以进一步解释。

相关问题