嗨,我有一个包含Drawable
的ImageView
,我想知道这个Drawable
的实际大小(宽度和高度)。请问我怎样才能知道真正的尺寸?
我试过了,但它不工作:
final ImageView img = (ImageView) findViewById(R.id.imagePlan);
img.setImageResource(R.drawable.gratuit);
System.out.println("w=="+img.getDrawable().getIntrinsicWidth()+" h=="+img.getDrawable().getIntrinsicHeight());
谢谢
首先你必须转换成可绘制的位图,然后你可以得到图像的高度和宽度。
尝试下面的代码:-
BitmapDrawable bd=(BitmapDrawable) this.getResources().getDrawable(imageID);
double imageHeight = bd.getBitmap().getHeight();
double imageWidth = bd.getBitmap().getWidth();
你可能得到的宽度和高度都是零,因为,可绘制的还没有被你测量,
img.post(new Runnable() {
@Override
public void run() {
System.out.println("w=="+img.getDrawable().getIntrinsicWidth()+" h=="+img.getDrawable().getIntrinsicHeight());
}
})
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.sample_image, options);
int w = bmp.getWidth();
int h = bmp.getHeight();
通过将资源解码为位图,您可以获得实际的宽度和高度。
final ImageView img = (ImageView) findViewById(R.id.gratuit);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
img.setImageBitmap(bitmap);
如果是VectorDrawable您可以使用intrinsicHeight
和intrinsicWidth
所以接受的答案将是
val vd = this.resources.getDrawable(cardInput.card!!.brand.icon) as VectorDrawable
val imageHeight = vd.intrinsicHeight
val imageWidth = vd.intrinsicWidth