Search code examples
androidimageviewscale

Get image dimensions after it draws in screen


I have an ImageView with MathParent height and width
In my activity it loads a pic from resource to ImageView. How can i get width and height of the picture inside the ImageView AFTER it has been scaled.
I have not set the android:scaleType in XML
these dimensions i mean!
Screenshot


Solution

  • You can do a lot with the matrix the view uses to display the image.

    Here I calculate the scale the image is drawn at:

    private float scaleOfImageView(ImageView image) {
        float[] coords = new float[]{0, 0, 1, 1};
        Matrix matrix = image.getImageMatrix();
        matrix.mapPoints(coords);
        return coords[2] - coords[0]; //xscale, method assumes maintaining aspect ratio
    }
    

    Applying the scale to the image dimensions gives the displayed image size:

    private void logImageDisplaySize(ImageView image) {
        Drawable drawable = image.getDrawable();
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        float scale = scaleOfImageView(image);
        float displayedWidth = scale * width;
        float displayedHeight = scale * height;
        Log.d(TAG, String.format("Image drawn at scale: %.2f => %.2f x %.2f",
                scale, displayedWidth, displayedHeight));
    }
    

    I suspect you don't really care about the image size, I suspect you want to map touch points back to a coordinate on the image, this answer shows how to do this (also using the image matrix): https://stackoverflow.com/a/9945896/360211