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.
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.
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); } ... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With