解決android 自定義camera變形的問題
阿新 • • 發佈:2019-01-30
主要是因為surfaceview的顯示大小和camera預覽Size不匹配導致的。
下面這一段,我也是借鑑別人然後修改傳入的surfaceview寬高位置就可以了。
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();//獲取所有支援的camera尺寸 Log.d("jxd","optionSize : mSurfaceView "+mSurfaceView.getWidth()+" * "+mSurfaceView.getHeight()); Camera.Size optionSize = getOptimalPreviewSize(sizeList, mSurfaceView.getHeight(), mSurfaceView.getWidth());//獲取一個最為適配的camera.size Log.d("jxd","optionSize : "+optionSize.width+" * "+optionSize.height); parameters.setPreviewSize(optionSize.width,optionSize.height);//把camera.size賦值到parameters mCamera.setParameters(parameters); //通過SurfaceView顯示預覽 mCamera.setPreviewDisplay(mHolder); //開始預覽 mCamera.startPreview();
尋找合適的size
/** * 解決預覽變形問題 * @param sizes * @param w * @param h * @return */ private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return null; Camera.Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size 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); } } // Cannot find the one match the aspect ratio, ignore the requirement 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; }