1 /* 2 * Copyright (C) 2023 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.google.android.wallpaper.weathereffects.graphics.utils 18 19 import android.graphics.Matrix 20 import android.util.SizeF 21 22 /** Helper functions for matrix operations. */ 23 object MatrixUtils { 24 /** Returns a [Matrix] that crops the image and centers to the screen. */ centerCropMatrixnull25 fun centerCropMatrix(surfaceSize: SizeF, imageSize: SizeF): Matrix { 26 val widthScale = surfaceSize.width / imageSize.width 27 val heightScale = surfaceSize.height / imageSize.height 28 val scale = maxOf(widthScale, heightScale) 29 30 return Matrix(Matrix.IDENTITY_MATRIX).apply { 31 // Move the origin of the image to its center. 32 postTranslate(-imageSize.width / 2f, -imageSize.height / 2f) 33 // Apply scale. 34 postScale(scale, scale) 35 // Translate back to the center of the screen. 36 postTranslate(surfaceSize.width / 2f, surfaceSize.height / 2f) 37 } 38 } 39 } 40