Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView be a square with dynamic width?

I have a GridView with ImageViews inside. I have 3 of them for each row. I can set correctly the width with WRAP_CONTENT and scaleType = CENTER_CROP, but I don't know how to set the ImageView's size to be a square. Here's what I did until now, it seems to be ok except the height, that is "static":

imageView = new ImageView(context);      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, 300)); 

I'm doing it inside an adapter.

like image 912
Andrea Avatar asked May 12 '13 10:05

Andrea


People also ask

How do you square a picture on android?

The best way for square image is use ConstraintLayout with constraintDimensionRatio Without give fix height/width. android:scaleType="centerCrop" is really a bad idea and screws up the pictures. This worked great; didn't do centerCrop, of course.


2 Answers

The best option is to subclass ImageView yourself, overriding the measure pass:

public class SquareImageView  extends ImageView {    ...    @Override   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     super.onMeasure(widthMeasureSpec, heightMeasureSpec);      int width = getMeasuredWidth();     setMeasuredDimension(width, width);   }    ...  } 
like image 115
a.bertucci Avatar answered Oct 06 '22 08:10

a.bertucci


The other answer works fine. This is just an extension of bertucci's solution to make an ImageView with square width and height with respect to xml inflated layout.

Create a class, say a SquareImageView extending ImageView like this,

public class SquareImageView extends ImageView {      public SquareImageView(Context context) {         super(context);     }      public SquareImageView(Context context, AttributeSet attrs) {         super(context, attrs);     }      public SquareImageView(Context context, AttributeSet attrs, int defStyle) {         super(context, attrs, defStyle);     }      @Override     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {         super.onMeasure(widthMeasureSpec, heightMeasureSpec);          int width = getMeasuredWidth();         setMeasuredDimension(width, width);     }  } 

Now, in your xml do this,

        <com.packagepath.tothis.SquareImageView             android:id="@+id/Imageview"             android:layout_width="fill_parent"             android:layout_height="fill_parent" /> 

If you need an ImageView not to be dynamically created in program, instead, to be fixed in xml, then this implementation will be helpful.

like image 44
Andro Selva Avatar answered Oct 06 '22 08:10

Andro Selva