Skip to content

Instantly share code, notes, and snippets.

@eoinfogarty
Created November 9, 2015 02:50
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 eoinfogarty/f7a95a19afecc52e8d16 to your computer and use it in GitHub Desktop.
Save eoinfogarty/f7a95a19afecc52e8d16 to your computer and use it in GitHub Desktop.
imageview with ratio that can be set based on width
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by Eoin Fogarty on 2015/11/06.
*
* Clamps an image ratio
* between 3(width) and 2(height) and 1(width) and 2(height)
*/
public class RatioImageView extends ImageView {
public static final float LIST_IMAGE_MAX_HEIGHT_RATIO = 2f / 1f;
public static final float LIST_IMAGE_MIN_HEIGHT_RATIO = 2f / 3f;
// by default the image ratio will be 1 to 1 ie square
private static final int DEFAULT_RATIO = 1;
private float mRatio = DEFAULT_RATIO;
public RatioImageView(@NonNull Context context) {
super(context);
}
public RatioImageView(@NonNull Context context, AttributeSet attrs) {
super(context, attrs);
}
public RatioImageView(@NonNull Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), (int) (getMeasuredWidth() * mRatio));
}
public void setRatio(float ratio) {
//clamp ratio between 3/2 and 1/2
mRatio = Math.max(LIST_IMAGE_MIN_HEIGHT_RATIO, ratio);
mRatio = Math.min(LIST_IMAGE_MAX_HEIGHT_RATIO, mRatio);
requestLayout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment