Created
September 19, 2014 11:13
-
-
Save JohnMars/ced70ce0dd24646e6b13 to your computer and use it in GitHub Desktop.
Aspect Ration Layout
This file contains hidden or 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
| <?xml version="1.0" encoding="utf-8"?> | |
| <resources> | |
| <declare-styleable name="FixedAspectLayout"> | |
| <attr name="aspectRatio" format="float"/> | |
| </declare-styleable> | |
| </resources> |
This file contains hidden or 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
| 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