Created
April 20, 2017 20:33
-
-
Save aashreys/02e3133769b25ccb7057bd963fb4878c to your computer and use it in GitHub Desktop.
An ImageView which can be locked to an aspect ratio.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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