步驟1:
根據(jù) Camera
支持的尺寸和當前屏幕
的尺寸選擇一個合適的預覽尺寸俭正,大概的代碼如下:
private static Camera.Size getOptimalSize(int w, int h) {
Camera.Parameters cameraParameter = camera.getParameters();
List<Camera.Size> sizes = cameraParameter.getSupportedPreviewSizes()
final double ASPECT_TOLERANCE = 0.1;
// 豎屏是 h/w, 橫屏是 w/h
double targetRatio = (double) h / w;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
步驟2:
獲取了合適的 Camera.Size
之后會發(fā)現(xiàn)部分機型胚鸯,比如小米Mix3
支持的相機尺寸如下:
width:1920,height:1440
width:1920,height:1080
width:1600,height:1200
width:1280,height:960
width:1280,height:720
width:1280,height:640
width:800,height:600
width:720,height:480
width:640,height:480
width:640,height:360
width:352,height:288
width:320,height:240
但是它的屏幕尺寸是:2340 * 1080辞嗡,這樣獲取的最合適的 Camera.Size
是 1920 * 1080,這是就會發(fā)現(xiàn)預覽界面被拉長了汗侵,想象一下 1920 的高度放到 2340 的高度上肯定會被拉長忿峻,這個時候就需要對顯示預覽界面的 View 做一下縮放
和 偏移
操作了润努,大概的代碼如下:
public Matrix calculateSurfaceHolderTransform() {
// 預覽 View 的大小,比如 SurfaceView
int viewHeight = configManager.getScreenResolution().y;
int viewWidth = configManager.getScreenResolution().x;
// 相機選擇的預覽尺寸
int cameraHeight = configManager.getCameraResolution().x;
int cameraWidth = configManager.getCameraResolution().y;
// 計算出將相機的尺寸 => View 的尺寸需要的縮放倍數(shù)
float ratioPreview = (float) cameraWidth / cameraHeight;
float ratioView = (float) viewWidth / viewHeight;
float scaleX, scaleY;
if (ratioView < ratioPreview) {
scaleX = ratioPreview / ratioView;
scaleY = 1;
} else {
scaleX = 1;
scaleY = ratioView / ratioPreview;
}
// 計算出 View 的偏移量
float scaledWidth = viewWidth * scaleX;
float scaledHeight = viewHeight * scaleY;
float dx = (viewWidth - scaledWidth) / 2;
float dy = (viewHeight - scaledHeight) / 2;
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
matrix.postTranslate(dx, dy);
return matrix;
}
如果你的預覽 View 是 SurfaceView
:
Matrix matrix = CameraManager.get().calculateSurfaceHolderTransform();
float[] values = new float[9];
matrix.getValues(values);
surfaceView.setTranslationX(values[Matrix.MTRANS_X]);
surfaceView.setTranslationY(values[Matrix.MTRANS_Y]);
surfaceView.setScaleX(values[Matrix.MSCALE_X]);
surfaceView.setScaleY(values[Matrix.MSCALE_Y]);
surfaceView.invalidate();
如果你的預覽 View 是 TextureView
更加簡單:
Matrix matrix = CameraManager.get().calculateSurfaceHolderTransform();
textureView.setTransform(matrix);
參考:
ZxingView