How to get the Dimensions of a Drawable in an ImageView?

notme picture notme · Jan 10, 2011 · Viewed 68k times · Source

What is the best way to retrieve the dimensions of the Drawable in an ImageView?

My ImageView has an Init-Method where i create the ImageView:

private void init() {
    coverImg = new ImageView(context);
    coverImg.setScaleType(ScaleType.FIT_START);
    coverImg.setImageDrawable(getResources().getDrawable(R.drawable.store_blind_cover));
    addView(coverImg);
}

At some point during the layout oder measure process i need the exact dimensions of the Drawable to adjust the rest of my Components around it.

coverImg.getHeight() and coverImg.getMeasuredHeight() don't return the results that i need and if i use coverImg.getDrawable().getBounds() i get the dimensions before it was scaled by the ImageView.

Thanks for your help!

Answer

Kevin Coppock picture Kevin Coppock · Jan 10, 2011

Just tried this out and it works for me:

int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        // Remove after the first run so it doesn't fire forever
        iv.getViewTreeObserver().removeOnPreDrawListener(this);
        finalHeight = iv.getMeasuredHeight();
        finalWidth = iv.getMeasuredWidth();
        tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
        return true;
    }
});

The ViewTreeObserver will let you monitor the layout just prior to drawing it (i.e. everything has been measured already) and from here you can get the scaled measurements from the ImageView.