1 /*
2  * Copyright 2018 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.pump.widget;
18 
19 import android.content.Context;
20 import android.graphics.drawable.Drawable;
21 import android.util.AttributeSet;
22 
23 import androidx.annotation.AttrRes;
24 import androidx.annotation.NonNull;
25 import androidx.annotation.Nullable;
26 import androidx.annotation.UiThread;
27 
28 @UiThread
29 public class AspectRatioImageView extends UriImageView {
AspectRatioImageView(@onNull Context context)30     public AspectRatioImageView(@NonNull Context context) {
31         super(context);
32     }
33 
AspectRatioImageView(@onNull Context context, @Nullable AttributeSet attrs)34     public AspectRatioImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
35         super(context, attrs);
36     }
37 
AspectRatioImageView(@onNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr)38     public AspectRatioImageView(@NonNull Context context, @Nullable AttributeSet attrs,
39             @AttrRes int defStyleAttr) {
40         super(context, attrs, defStyleAttr);
41     }
42 
43     @Override
onMeasure(int widthMeasureSpec, int heightMeasureSpec)44     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
45         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
46 
47         // TODO Make aspect ratio configurable
48         int aspectWidth = 16;
49         int aspectHeight = 9;
50 
51         Drawable drawable = getDrawable();
52         if (drawable != null) {
53             // TODO Landscape/Portrait preference should be configurable
54             int intrinsicWidth = drawable.getIntrinsicWidth();
55             int intrinsicHeight = drawable.getIntrinsicHeight();
56 
57             if (intrinsicWidth < intrinsicHeight) {
58                 aspectWidth = 2;
59                 aspectHeight = 3;
60             }
61         }
62 
63         int width = getMeasuredWidth();
64         int height = width * aspectHeight / aspectWidth;
65         setMeasuredDimension(width, height);
66     }
67 }
68