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

问题描述 投票:24回答:2

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

android imageview android-bitmap dimensions
2个回答
81
投票

您可以通过使用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();      

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());

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

© www.soinside.com 2019 - 2024. All rights reserved.