1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| @SuppressWarnings("unused") public class FixedAspectRatioFrameLayout extends FrameLayout { private static final int FIXED_WIDTH = 0; private static final int FIXED_HEIGHT = 1; private int mAspectRatioWidth = 0; private int mAspectRatioHeight = 0; private int mFixedAspect;
public FixedAspectRatioFrameLayout(Context context) { super(context); }
public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); }
public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); }
@TargetApi(21) public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); }
private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioView); mAspectRatioWidth = a.getInt(R.styleable.FixedAspectRatioView_aspectRatioWidth, 0); mAspectRatioHeight = a.getInt(R.styleable.FixedAspectRatioView_aspectRatioHeight, 0); mFixedAspect = a.getInt(R.styleable.FixedAspectRatioView_fixedAspect, FIXED_WIDTH); a.recycle(); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mAspectRatioHeight == 0 || mAspectRatioWidth == 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } else { int originalWidth = MeasureSpec.getSize(widthMeasureSpec); int originalHeight = MeasureSpec.getSize(heightMeasureSpec); int calculatedHeight = originalWidth * mAspectRatioHeight / mAspectRatioWidth; int expectedWidth, expectedHeight; if (mFixedAspect == FIXED_WIDTH) { expectedWidth = originalWidth; expectedHeight = calculatedHeight; } else { expectedWidth = originalHeight * mAspectRatioWidth / mAspectRatioHeight; expectedHeight = originalHeight; } super.onMeasure(MeasureSpec.makeMeasureSpec(expectedWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(expectedHeight, MeasureSpec.EXACTLY)); } } }
|