Skip to content

Instantly share code, notes, and snippets.

@neilbantoc
Last active August 29, 2015 13:56
Show Gist options
  • Save neilbantoc/8820961 to your computer and use it in GitHub Desktop.
Save neilbantoc/8820961 to your computer and use it in GitHub Desktop.
An ImageView that adjusts its height according to a given ratio. This is useful for dynamic layouts where the ImageView's height must adjust accordingly when its width changes, say, for instances where its width is fill_parent.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
/*
* An ImageView that adjusts its height according
* to a given ratio. This is useful for dynamic layouts where
* the ImageView's height must adjust accordingly when its width
* changes, say, for instances where its width is fill_parent.
*
* To set aspect ratio in xml file, add this to your attrs.xml file;
* <resources>
* <declare-styleable name="AspectRatioImageView">
* <attr name="aspectRatioHorizontal" format="integer"/>
* <attr name="aspectRatioVertical" format="integer"/>
* <attr name="aspectRatio" format="float"/>
* </declare-styleable>
* </resources>
*
* Then use as follows:
* <your.package.here.AspectRatioImageView
* android:id="@+id/cover_photo"
* android:layout_width="fill_parent"
* android:layout_height="wrap_content"
* android:scaleType="centerCrop"
* app:aspectRatioHorizontal="16"
* app:aspectRatioVertical="10" />
*/
public class AspectRatioImageView extends ImageView {
private float aspectRatio;
public AspectRatioImageView(Context context) {
this(context, null);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
int horizontalRatio = 0, verticalRatio = 0;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AspectRatioImageView, 0, 0);
for (int x = 0; x < typedArray.length(); x++) {
int index = typedArray.getIndex(x);
switch (index) {
case R.styleable.AspectRatioImageView_aspectRatioHorizontal:
horizontalRatio = typedArray.getInteger(index, 0);
break;
case R.styleable.AspectRatioImageView_aspectRatioVertical:
verticalRatio = typedArray.getInteger(index, 0);
break;
case R.styleable.AspectRatioImageView_aspectRatio:
aspectRatio = typedArray.getFloat(index, 0);
break;
}
}
typedArray.recycle();
aspectRatio = horizontalRatio > 0 && verticalRatio > 0 ? (float)horizontalRatio/verticalRatio : aspectRatio;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (aspectRatio == 0)
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
else {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) (MeasureSpec.getSize(widthMeasureSpec) / aspectRatio);
setMeasuredDimension(width, height);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment