繁体   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