1

I simply have an image from phone gallery, most of them are either portrait i.e. (height > width) or landscape (width > height)

i want to display each photo in a square shape each image is larger than the imageview that i am going to put it into, that is ok, i want the image to be cropped and centered,

I have been using the imageview scaleType

FitXY

it gives me what i want, a square, but it doesn't keep the aspect ratio, so image looks distorted.

so i use

centerCrop

the aspect ratio is kept, but the imageview is no longer a square (due to aspect ratio is being kept)

i guess what i want is both centerCrop + fitXY, i.e. i want a sqaure image with aspect ratio kept

how can i do this?

XyzNullPointer
  • 275
  • 6
  • 11

1 Answers1

0

You can create custom ImageView which will use picture height/width as it's own and adapt width/height to keep aspect ratio.

Override onMeasure like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Drawable d = getDrawable();

    if (d != null) {
        // ceil not round - avoid thin vertical gaps along the left/right edges
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) Math
                .ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

ImageView with this onMeasure will stretch picture to it's width and adapt it's height to keep aspect ratio of the image. You can also set the same height as a width to get square image.

Possibly related to: Android ImageView adjusting parent's height and fitting width

Community
  • 1
  • 1
Lingviston
  • 5,479
  • 5
  • 35
  • 67
  • this doesn't work sir. i already hard coded my image view to a square, say 100 by 100px. so the width and height being returned in on measure is always correct, i.e. 100 by 100, i don't need to change that. the problem is that the image coming in is 60px by 100 pixel, the image being loaded is not square but a vertical triangle, i want it to be full square – XyzNullPointer Jun 16 '13 at 18:23