1 /* 2 * Copyright 2015 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.camera2raw; 18 19 import android.content.Context; 20 import android.util.AttributeSet; 21 import android.view.TextureView; 22 23 /** 24 * A {@link TextureView} that can be adjusted to a specified aspect ratio. 25 */ 26 public class AutoFitTextureView extends TextureView { 27 28 private int mRatioWidth = 0; 29 private int mRatioHeight = 0; 30 AutoFitTextureView(Context context)31 public AutoFitTextureView(Context context) { 32 this(context, null); 33 } 34 AutoFitTextureView(Context context, AttributeSet attrs)35 public AutoFitTextureView(Context context, AttributeSet attrs) { 36 this(context, attrs, 0); 37 } 38 AutoFitTextureView(Context context, AttributeSet attrs, int defStyle)39 public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) { 40 super(context, attrs, defStyle); 41 } 42 43 /** 44 * Sets the aspect ratio for this view. The size of the view will be measured based on the ratio 45 * calculated from the parameters. Note that the actual sizes of parameters don't matter, that 46 * is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result. 47 * 48 * @param width Relative horizontal size 49 * @param height Relative vertical size 50 */ setAspectRatio(int width, int height)51 public void setAspectRatio(int width, int height) { 52 if (width < 0 || height < 0) { 53 throw new IllegalArgumentException("Size cannot be negative."); 54 } 55 if (mRatioWidth == width && mRatioHeight == height) { 56 return; 57 } 58 mRatioWidth = width; 59 mRatioHeight = height; 60 requestLayout(); 61 } 62 63 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)64 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 65 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 66 int width = MeasureSpec.getSize(widthMeasureSpec); 67 int height = MeasureSpec.getSize(heightMeasureSpec); 68 if (0 == mRatioWidth || 0 == mRatioHeight) { 69 setMeasuredDimension(width, height); 70 } else { 71 if (width < height * mRatioWidth / mRatioHeight) { 72 setMeasuredDimension(width, width * mRatioHeight / mRatioWidth); 73 } else { 74 setMeasuredDimension(height * mRatioWidth / mRatioHeight, height); 75 } 76 } 77 } 78 79 } 80