Get drawable displayed size after scaling

2019-02-27 21:50发布

问题:

here's my problem:
How can get the displayed size of the drawable inside an ImageView in pixel after scalling, assuming that the ImageView size isn't equal to the scaled drawable?

A lot of methods just return the original size of the Drawable or just the size of the ImageView.

Here is a picture describing what I want :

http://image.noelshack.com/fichiers/2013/06/1360144144-sans-titre.png

1 --> ImageView Size
2 --> The scaled image size that I want to get in px

Thank you.

回答1:

From the image you posted I assume you have scaleType of FIT_CENTER (or CENTER_INSIDE with drawable bigger than imageView) on your ImageView

so you can calculate displayed size like so

    boolean landscape = imageView.getWidth() > imageView.getHeight();

    float displayedHeight;
    float displayedWidth;

    if (landscape){
        displayedHeight = imageView.getHeight();
        displayedWidth = (float) drawableWidth * imageView.getHeight() / drawableHeight;
    } else {
        displayedHeight = (float) drawableHeight * imageView.getWidth() / drawableWidth;
        displayedWidth = imageView.getWidth();
    }

Note: code not simplified for readability.

Another more robust approach that can be applied to all scaleTypes is to use the matrix that imageView used to scale the image

float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
float displayedWidth = drawableWidth * f[Matrix.MSCALE_X];
float displayedHeight = drawableHeight * f[Matrix.MSCALE_Y];