Skip to content

Instantly share code, notes, and snippets.

@CMingTseng
Forked from unosk/AspectRatioImageView.java
Created March 22, 2019 22:08
Show Gist options
  • Save CMingTseng/02460500c315aa766c53a00b293cd35a to your computer and use it in GitHub Desktop.
Save CMingTseng/02460500c315aa766c53a00b293cd35a to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* TODO: Add a class header comment!
*/
public class AspectRatioImageView extends ImageView {
private float mAspectRatio;
public AspectRatioImageView(Context context) {
this(context, null);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AspectRatioImageView);
mAspectRatio = a.getFloat(R.styleable.AspectRatioImageView_aspect_ratio, -1);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mAspectRatio > 0) {
int width = getMeasuredWidth();
int height = (int) (width * mAspectRatio);
setMeasuredDimension(width, height);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="AspectRatioImageView">
<attr name="aspect_ratio" format="float" />
</declare-styleable>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment