關於拉伸問題,要使預覽不變形,需要使用Matrix:
首先把視頻區移動到View區,使兩者中心點重合。
matrix.preTranslate((textureViewWidth - viewWidth) / 2, (textureViewHeight - viewHeight) / 2);
其次,因為默認視頻是fitXY的形式顯示的,所以首先要縮放還原回來。
matrix.preScale(viewWidth/ textureViewWidth, viewHeight/ textureViewHeight);
最后等比例放大或縮小,直到視頻區的一邊和View一邊相等,不相等則留白。
int rotation = getWindowManager().getDefaultDisplay().getRotation(); Matrix matrix = new Matrix(); RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth()); float centerX = viewRect.centerX(); float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); float scale = Math.max( (float) viewHeight / mPreviewSize.getHeight(), (float) viewWidth / mPreviewSize.getWidth()); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate(90 * (rotation - 2), centerX, centerY); } else if (Surface.ROTATION_180 == rotation) { matrix.postRotate(180, centerX, centerY); } mTextureView.setTransform(matrix);
不考慮全屏的情況下設置TextureView大小為可支持的最大size即可:
Size largest = Collections.max( Arrays.asList(mMap.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
要使TextureView全屏,重寫TextureView的onMeasure方法:
@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 { //設置為大於判斷時,textureView全屏預覽,小於號時,按比例留白預覽 if (width > height * mRatioWidth / mRatioHeight) { setMeasuredDimension(width, width * mRatioHeight / mRatioWidth); } else { setMeasuredDimension(height * mRatioWidth / mRatioHeight, height); } } }
這段代碼使得TextureView在寬高都不超過手機屏幕的情況下最大化顯示。
解決方案是,讓TextureView總是達到最大邊界,超出部分不進行預覽,但實際上還是能拍到的
