Skip to content

Instantly share code, notes, and snippets.

@iamdeveloper-lopez
Created March 18, 2019 06:52
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 iamdeveloper-lopez/38f80f02b6e814d1097bf44f60f24a42 to your computer and use it in GitHub Desktop.
Save iamdeveloper-lopez/38f80f02b6e814d1097bf44f60f24a42 to your computer and use it in GitHub Desktop.
An ImageView layout that maintains a consistent width to height aspect ratio.
public class DynamicHeightImageView extends ImageView {
private double mHeightRatio;
public DynamicHeightImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DynamicHeightImageView(Context context) {
super(context);
}
public void setHeightRatio(double ratio) {
if (ratio != mHeightRatio) {
mHeightRatio = ratio;
requestLayout();
}
}
public double getHeightRatio() {
return mHeightRatio;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mHeightRatio > 0.0) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) (width * mHeightRatio);
setMeasuredDimension(width, height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment