How to get an Android Camera2 with 1:1 ratio like Instagram?

前端 未结 4 1624
渐次进展
渐次进展 2021-02-13 14:21

My question is very simple:

How to get an Android android.hardware.Camera2 with 1:1 ratio and without deformation like Instagram?

4条回答
  •  梦如初夏
    2021-02-13 14:52

    Thanks @CommonsWare.

    I followed your advice using negative margin (top and bottom) and it works.

    To do that, I just update AutoFitTextureView the GoogeSamples project android-Camera2Basic this way:

    public class AutoFitTextureView extends TextureView {
    
        //...
        private boolean mWithMargin = false;
    
        //...
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, widthMeasureSpec);
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int margin = (height - width) / 2;
    
            if(!mWithMargin) {
                mWithMargin = true;
                ViewGroup.MarginLayoutParams margins = ViewGroup.MarginLayoutParams.class.cast(getLayoutParams());
                margins.topMargin = -margin;
                margins.bottomMargin = -margin;
                margins.leftMargin = 0;
                margins.rightMargin = 0;
                setLayoutParams(margins);
            }
    
            if (0 == mRatioWidth || 0 == mRatioHeight) {
                setMeasuredDimension(width, height);
            } else {
                if (width < height) {
                    setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
                } else {
                    setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
                }
            }
        }
    }
    

提交回复
热议问题