Skip to content

Instantly share code, notes, and snippets.

@JohnMars
Created September 19, 2014 11:13
Show Gist options
  • Select an option

  • Save JohnMars/ced70ce0dd24646e6b13 to your computer and use it in GitHub Desktop.

Select an option

Save JohnMars/ced70ce0dd24646e6b13 to your computer and use it in GitHub Desktop.
Aspect Ration Layout
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FixedAspectLayout">
<attr name="aspectRatio" format="float"/>
</declare-styleable>
</resources>
public class FixedAspectLayout extends FrameLayout {
private float aspect = 1.0f;
// .. alternative constructors omitted
public FixedAspectLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FixedAspectLayout);
aspect = a.getFloat(R.styleable.FixedAspectLayout_aspectRatio, 1.0f);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = MeasureSpec.getSize(heightMeasureSpec);
if (w == 0) {
h = 0;
} else if (h / w < aspect) {
w = (int)(h / aspect);
} else {
h = (int)(w * aspect);
}
super.onMeasure(
MeasureSpec.makeMeasureSpec(w,
MeasureSpec.getMode(widthMeasureSpec)),
MeasureSpec.makeMeasureSpec(h,
MeasureSpec.getMode(heightMeasureSpec)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment