Skip to content Skip to sidebar Skip to footer

Custom Camera Preview Issue (stretch)

I'm having a problem with my camera app. My app has: 1) a CameraActivity.class and 2) a CameraPreview.class. CameraPreview implement a surfaceView where it's called from CameraAct

Solution 1:

I added the code below to my camera preview class and it works for most devices. Just so you are aware, the camera library in Android is horrible and a huge pain to work with.

Put this function in your CameraPreview class:

private Camera.Size getOptimalSize(List<Camera.Size> sizes, int h, int w){
    finaldouble ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w/h;

    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;
}

In your surefaceCreated function, add this before you start your preview:

Camera.ParameterscameraParameters= mCamera.getParameters();
List<Camera.Size> previewSizes = cameraParameters.getSupportedPreviewSizes();
Camera.SizeoptimalPreviewSize= getOptimalSize(previewSizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
cameraParameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
mCamera.setParameters(cameraParameters);

Edit: Also, I'm not sure if you want

mHolder.setFixedSize(100, 100);

in your constructor.

Post a Comment for "Custom Camera Preview Issue (stretch)"