Trying to get the display size of an image in an ImageView

Viewed 43772

I'm trying to get the real size of an image displayed in an image view. Actually my image is larger than the screen and the imageview is resizing the image to diplay it. I'm looking for this new size.

I've tried to override the onDraw method of the ImageView in a custom view but I'm not getting the correct height and width...

public class LandImageView extends ImageView
{
    public LandImageView( Context context )
    {
        super( context );
    }

    public LandImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public LandImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw( Canvas canvas )
    {
        super.onDraw( canvas );

        int test = this.getWidth();
        int test2 = this.getHeight();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
    }
}

Do you have any clues ?

14 Answers

You can use imageview's viewtreeobserver and addonDrawListener.

ViewTreeObserver vto = imageView.getViewTreeObserver();
    vto.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
        @Override
        public void onDraw() {

            float[] f = new float[9];
            imageView.getImageMatrix().getValues(f);

            // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
            final float scaleX = f[Matrix.MSCALE_X];
            final float scaleY = f[Matrix.MSCALE_Y];


            // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
            final Drawable d = imageView. getDrawable();
            final int origW = d.getIntrinsicWidth();
            final int origH = d.getIntrinsicHeight();

            // Calculate the actual dimensions
            final int actW = Math.round(origW * scaleX);
            final int actH = Math.round(origH * scaleY);

        }
    });

Simply can be used this code (in activity):

@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
    super.onWindowFocusChanged(hasWindowFocus);
    final ImageView imageView = findViewById(R.id.imageView);
    int width = imageView.getWidth(), height = imageView.getHeight();
}

In case the picture reaches the ends of the imageView.

Related