Created
November 9, 2015 02:50
imageview with ratio that can be set based on width
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
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