Skip to content

Instantly share code, notes, and snippets.

@unosk
Created April 5, 2015 05:10
Show Gist options
  • Save unosk/7b8a1c060e121978cd76 to your computer and use it in GitHub Desktop.
Save unosk/7b8a1c060e121978cd76 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