Compute aspect ratio properly

Change-Id: Ic4e1f20f7354b9ab5f4e9c7564d16d06324ec23d
Fixes: 64608152
Test: visual
This commit is contained in:
Fan Zhang
2017-08-15 11:00:04 -07:00
parent e3ca685321
commit 36717d4399
3 changed files with 123 additions and 3 deletions

View File

@@ -22,12 +22,14 @@ import android.widget.FrameLayout;
import com.android.settings.R;
/**
* A {@link FrameLayout} with customizable aspect ration.
* A {@link FrameLayout} with customizable aspect ratio.
* This is used to avoid dynamically calculating the height for the frame. Default aspect
* ratio will be 1 if none is set in layout attribute.
*/
public final class AspectRatioFrameLayout extends FrameLayout {
private static final float ASPECT_RATIO_CHANGE_THREASHOLD = 0.01f;
private float mAspectRatio = 1.0f;
public AspectRatioFrameLayout(Context context) {
@@ -51,7 +53,25 @@ public final class AspectRatioFrameLayout extends FrameLayout {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, (int) (widthMeasureSpec / mAspectRatio));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
if (width == 0 || height == 0) {
return;
}
final float viewAspectRatio = (float) width / height;
final float aspectRatioDiff = mAspectRatio - viewAspectRatio;
if (Math.abs(aspectRatioDiff) <= ASPECT_RATIO_CHANGE_THREASHOLD) {
// Close enough, skip.
return;
}
if (aspectRatioDiff > 0) {
width = (int) (height * mAspectRatio);
} else {
height = (int) (width / mAspectRatio);
}
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}