Skip to content

Instantly share code, notes, and snippets.

@tuanchauict
Created December 4, 2015 04:42
Show Gist options
  • Save tuanchauict/0798f7ac6fe160340c84 to your computer and use it in GitHub Desktop.
Save tuanchauict/0798f7ac6fe160340c84 to your computer and use it in GitHub Desktop.
AspectRatioFrameLayout for Android
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
* Created by tuanchauict on 11/18/15.
*/
public class AspectRatioFrameLayout extends FrameLayout {
private static final float DEFAULT_RATIO = 109.33f / 144f;
private float mViewAspectRatio; // width / height
private boolean mBaseWidth = true;
public AspectRatioFrameLayout(Context context) {
this(context, null);
}
public AspectRatioFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RatioView);
mViewAspectRatio = a.getFloat(R.styleable.RatioView_ratio, DEFAULT_RATIO);
mBaseWidth = a.getBoolean(R.styleable.RatioView_baseWidth, true);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width, height;
if (mBaseWidth) {
width = MeasureSpec.getSize(widthMeasureSpec);
int widthWithoutPadding = width - getPaddingLeft() - getPaddingRight();
int maxHeight = (int) (widthWithoutPadding / mViewAspectRatio);
height = maxHeight + getPaddingTop() + getPaddingBottom();
} else {
height = MeasureSpec.getSize(heightMeasureSpec);
int heightWithoutPadding = height - getPaddingTop() - getPaddingBottom();
int maxWidth = (int) (heightWithoutPadding * mViewAspectRatio);
width = maxWidth + getPaddingLeft() + getPaddingRight();
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RatioView">
<attr name="ratio" format="float"/>
<attr name="baseWidth" format="boolean"/>
</declare-styleable>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment