Fengjiang Li | fb16517 | 2024-03-04 15:36:08 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2024 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 | package com.android.launcher3 |
| 18 | |
| 19 | import android.graphics.Rect |
| 20 | |
| 21 | /** |
| 22 | * Fit [this] into [targetRect] with letter boxing. After calling this method, [this] will be |
| 23 | * modified to be letter boxed. |
| 24 | * |
| 25 | * @param targetRect target [Rect] that [this] should be fitted into |
| 26 | */ |
| 27 | fun Rect.letterBox(targetRect: Rect) { |
| 28 | letterBox(targetRect, this) |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Fit [this] into [targetRect] with letter boxing. After calling this method, [resultRect] will be |
| 33 | * modified to be letter boxed. |
| 34 | * |
| 35 | * @param targetRect target [Rect] that [this] should be fitted into |
| 36 | * @param resultRect the letter boxed [Rect] |
| 37 | */ |
| 38 | fun Rect.letterBox(targetRect: Rect, resultRect: Rect) { |
| 39 | val widthRatio: Float = 1f * targetRect.width() / width() |
| 40 | val heightRatio: Float = 1f * targetRect.height() / height() |
| 41 | if (widthRatio < heightRatio) { |
| 42 | val scaledHeight: Int = (widthRatio * height()).toInt() |
| 43 | val verticalPadding: Int = (targetRect.height() - scaledHeight) / 2 |
| 44 | resultRect.set( |
| 45 | targetRect.left, |
| 46 | targetRect.top + verticalPadding, |
| 47 | targetRect.right, |
| 48 | targetRect.bottom - verticalPadding |
| 49 | ) |
| 50 | } else { |
| 51 | val scaledWidth: Int = (heightRatio * width()).toInt() |
| 52 | val horizontalPadding: Int = (targetRect.width() - scaledWidth) / 2 |
| 53 | resultRect.set( |
| 54 | targetRect.left + horizontalPadding, |
| 55 | targetRect.top, |
| 56 | targetRect.right - horizontalPadding, |
| 57 | targetRect.bottom |
| 58 | ) |
| 59 | } |
| 60 | } |