ShawnZhang31
7/3/2019 - 9:03 AM

[Android AutoFitTextureView] Android Camera选择最适合的预览View #Android

[Android AutoFitTextureView] Android Camera选择最适合的预览View #Android

package com.panxsoft.crazystone_android;

import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;

/**
 * 可以自动调成长宽比以适配内容的{@link TextureView}
 */
public class AutoFitTextureView extends TextureView
{
    private int mRatioWidth = 0;
    private int mRatioHeight = 0;

    public AutoFitTextureView(Context context)
    {
        this(context, null);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    /**
     * 设置view的高宽比。
     * @param width 相对水平尺寸
     * @param height 相对高度尺寸
     */
    public void setAspectRatio(int width, int height)
    {
        if (width<0 || height<0)
        {
            throw new IllegalArgumentException("尺寸不能为负值!");
        }
        mRatioWidth = width;
        mRatioHeight = height;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (0==mRatioWidth || 0 ==mRatioHeight)
        {
            setMeasuredDimension(width, height);
        }else {
            if (width < height*mRatioWidth/mRatioHeight)
            {
                setMeasuredDimension(width, width*mRatioHeight/mRatioWidth);
            }else {
                setMeasuredDimension(height*mRatioWidth/mRatioHeight, height);
            }
        }
    }
}