我想获取位于ImageView
或背景图像中的图像位图的高度和宽度。请帮助我,任何帮助将不胜感激。
问问题
71653 次
2 回答
94
您可以通过使用 getWidth() 和 getHeight() 来获取 ImageView 的高度和宽度,但这不会为您提供图像的确切宽度和高度,首先要获取图像宽度高度,您需要将可绘制对象作为背景然后转换可绘制到 BitmapDrawable 以将图像作为位图从中获取,您可以像这里一样获取宽度和高度
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();
于 2012-01-16T13:15:32.820 回答
3
出于某种原因,接受的答案对我不起作用,而是像这样根据目标屏幕 dpi 实现了图像尺寸。
方法一
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
方法二
BitmapDrawable b = (BitmapDrawable)this.getResources().getDrawable(R.drawable.cake);
Log.d("MainActivity", "Image Width: " + b.getBitmap().getWidth());
它没有显示图像资源中的确切像素数,而是一个有意义的数字,也许有人可以进一步解释。
于 2018-01-05T11:10:11.567 回答