1 /*
2  * Copyright (C) 2021 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.example.android.apis.view;
18 
19 import android.content.Context;
20 import android.content.res.TypedArray;
21 import android.util.AttributeSet;
22 import android.util.Rational;
23 import android.widget.ImageView;
24 
25 import com.example.android.apis.R;
26 
27 /**
28  * Extended {@link ImageView} that keeps fixed aspect ratio (specified in layout file) when
29  * one of the dimension is in exact while the other one in wrap_content size mode.
30  */
31 public class FixedAspectRatioImageView extends ImageView {
32     private final Rational mAspectRatio;
33 
FixedAspectRatioImageView(Context context, AttributeSet attrs)34     public FixedAspectRatioImageView(Context context, AttributeSet attrs) {
35         super(context, attrs);
36         final TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
37                 R.styleable.FixedAspectRatioImageView, 0, 0);
38         try {
39             mAspectRatio = Rational.parseRational(
40                     a.getString(R.styleable.FixedAspectRatioImageView_aspectRatio));
41         } finally {
42             a.recycle();
43         }
44     }
45 
46     @Override
onMeasure(int widthMeasureSpec, int heightMeasureSpec)47     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
48         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
49         final int width, height;
50         if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
51                 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
52             width = MeasureSpec.getSize(widthMeasureSpec);
53             height = MeasureSpec.getSize(heightMeasureSpec);
54         } else if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
55             width = MeasureSpec.getSize(widthMeasureSpec);
56             height = (int) (width / mAspectRatio.floatValue());
57         } else {
58             height = MeasureSpec.getSize(heightMeasureSpec);
59             width = (int) (height * mAspectRatio.floatValue());
60         }
61         android.util.Log.d("DebugMe", "onMeasure w=" + width + " h=" + height);
62         setMeasuredDimension(width, height);
63     }
64 }