camera startPreview failed

后端 未结 5 1170
猫巷女王i
猫巷女王i 2021-01-02 09:46

I am creating a camera app but I have problems on startPreview, it sends me:

java.lang.RuntimeException: startPreview failed

h

5条回答
  •  礼貌的吻别
    2021-01-02 10:07

    Its late, but if someones looking for the answer

    The variables w and h are not the optimal preview sizes . You can get optimal preview sizes using the function

    public static Camera.Size getOptimalPreviewSize(List sizes, int w, int h) {
            final double ASPECT_TOLERANCE = 0.1;
            double targetRatio=(double)h / w;
            if (sizes == null) return null;
    
            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;
        }
    

    and you can call the function using

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    ..
    size=getOptimalPreviewSize(parameters.getSupportedPreviewSizes(), w, h);
     parameters.setPreviewSize(size.getWidth(), size.getHeight());
    ..
    
    }
    

提交回复
热议问题