1 /*
<lambda>null2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 package com.android.wallpaper.picker
19 
20 import android.content.Context
21 import android.util.AttributeSet
22 import android.widget.FrameLayout
23 import androidx.core.view.children
24 import com.android.wallpaper.util.ScreenSizeCalculator
25 
26 /**
27  * [FrameLayout] that sizes its children using a fixed aspect ratio that is the same as that of the
28  * display.
29  */
30 class DisplayAspectRatioFrameLayout(
31     context: Context,
32     attrs: AttributeSet?,
33 ) : FrameLayout(context, attrs) {
34 
35     override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
36         super.onMeasure(widthMeasureSpec, heightMeasureSpec)
37         val screenAspectRatio = ScreenSizeCalculator.getInstance().getScreenAspectRatio(context)
38         // We're always forcing the width based on the height. This will only work if the
39         // DisplayAspectRatioFrameLayout is allowed to stretch to fill its parent (for example if
40         // the parent is a vertical LinearLayout and the DisplayAspectRatioFrameLayout has a height
41         // if 0 and a weight of 1.
42         // However we make sure that the width of the children never exceeds the width of the parent
43         //
44         // If you need to use this class to force the height dimension based on the width instead,
45         // you will need to flip the logic below.
46         children.forEach { child ->
47             val childWidth =
48                 (child.measuredHeight / screenAspectRatio).toInt().coerceAtMost(measuredWidth)
49             child.measure(
50                 MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY),
51                 MeasureSpec.makeMeasureSpec(
52                     if (childWidth < measuredWidth) {
53                         child.measuredHeight
54                     } else {
55                         (childWidth * screenAspectRatio).toInt()
56                     },
57                     MeasureSpec.EXACTLY,
58                 ),
59             )
60         }
61     }
62 }
63