Reputation: 33866
I have a gallery in my app. My photos are from the internet, so they are added dynamically. My gallery doesn't crop them to all be a perfect square. I would like to do this just to make my gallery look better. I tried this in my XML;
ImageView
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
But because I am adding the image dynamically and not from src
in xml, this wont work. Anyone know how to do this another way? I cant find anything on how to do it when added dynamically. Thanks in advance.
Upvotes: 1
Views: 1940
Reputation: 381
If i am not getting it wrong we can do it with
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Upvotes: 3
Reputation: 2456
Are you laying the images out in a GridView
? If so then the following will work. (If not, something similar might work but not tested by me).
Firstly it is actually a bit tricky to force a view to be square, as the width and height are measured separately. You can refer to Simple way to do dynamic but square layout for some ideas. The simplest one (I think) is to create a new view inheriting from ImageView
but overriding onMeasure()
, e.g.
public class SquareImageView {
// add usual constructors here
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// this will change the height to match the measured width
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
Then change your layout xml to create instances of SquareImageView
instead of ImageView
. I think the rest of your attributes are OK, in particular android:scaleType="centerCrop"
will ensure the image fills up the whole square.
After this, you download your image from whatever source into a Bitmap
instance, then call imageView.setImageBitmap(bitmap)
to display the image cropped to a perfect square. And that's it!
Upvotes: 0
Reputation: 8488
If you need to scale the images dynamically you can use scaled bitmap method of bitmap to specifying size of your scaled down/up image programaticaly. Something like this:
Bitmap scaledBitmap = Bitmap.createScaledBitmap(unscaledBitmap, wantedWidth, wantedHeight, true);
For scaling details you can follow below link:
http://developer.sonymobile.com/2011/06/27/how-to-scale-images-for-your-android-application/
Upvotes: 1