Skip to content

Instantly share code, notes, and snippets.

@aashreys
Created April 20, 2017 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aashreys/02e3133769b25ccb7057bd963fb4878c to your computer and use it in GitHub Desktop.
Save aashreys/02e3133769b25ccb7057bd963fb4878c to your computer and use it in GitHub Desktop.
An ImageView which can be locked to an aspect ratio.
public class AspectRatioImageView extends ImageView {
private float widthToHeightRatio;
public AspectRatioImageView(Context context) {
super(context);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setWidthToHeightRatio(float widthToHeightRatio) {
this.widthToHeightRatio = widthToHeightRatio;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (widthToHeightRatio > 0) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
int calculatedHeight = (int) (originalWidth / widthToHeightRatio);
super.onMeasure(
MeasureSpec.makeMeasureSpec(originalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(calculatedHeight, MeasureSpec.EXACTLY)
);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment