android textureview处理预览摄像头变形问题

当TextureView的大小和匹配到的摄像头PreviewSize宽高比例不完全一致时,TextureView可通过setTransform函数对预览画面进行处理后再显示到TextureView,如下对图形居中裁剪:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public void sizeNotify(Camera.Size size) {
float viewWidth = getWidth();
float viewHeight = getHeight();

float scaleX = 1.0f;
float scaleY = 1.0f;
int mPreviewWidth = size.width;
int mPreviewHeight = size.height;
if(viewWidth < viewHeight) {
mPreviewWidth = size.height;
mPreviewHeight = size.width;
}


if (mPreviewWidth > viewWidth && mPreviewHeight > viewHeight) {
scaleX = mPreviewWidth / viewWidth;
scaleY = mPreviewHeight / viewHeight;
} else if (mPreviewWidth < viewWidth && mPreviewHeight < viewHeight) {
scaleY = viewWidth / mPreviewWidth;
scaleX = viewHeight / mPreviewHeight;
} else if (viewWidth > mPreviewWidth) {
scaleY = (viewWidth / mPreviewWidth) / (viewHeight / mPreviewHeight);
} else if (viewHeight > mPreviewHeight) {
scaleX = (viewHeight / mPreviewHeight) / (viewWidth / mPreviewWidth);
}

// Calculate pivot points, in our case crop from center
int pivotPointX = (int) (viewWidth / 2);
int pivotPointY = (int) (viewHeight / 2);

Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY, pivotPointX, pivotPointY);
/*Log.e(TAG, "viewsize:" + viewWidth + " * " + viewHeight +
";prviewSize:" + mPreviewWidth + " * " + mPreviewHeight +
";scale:" + scaleX + " * " + scaleY +
";pivot:" + pivotPointX + " * " + pivotPointY);*/
setTransform(matrix);
}

TextureView中setTransform函数说明: Sets the transform to associate with this texture view. The specified transform applies to the underlying surface texture and does not affect the size or position of the view itself, only of its content.

Some transforms might prevent the content from drawing all the pixels contained within this view’s bounds. In such situations, make sure this texture view is not marked opaque.

坚持原创技术分享,您的支持将鼓励我继续创作!