'How to set size of camera preview in android

I am trying to create a custom camera in android. I want to set the exact size of the picture to be taken. I want that exact size to be what the user sees in the preview. How do I set that exact size? (By size I mean width and height: dimension)

I find the following verbiage in the android literatures:

If you want to set a specific size for your camera preview, set this in the surfaceChanged() method as noted in the comments above. When setting preview size, you must use values from getSupportedPreviewSizes(). Do not set arbitrary values in the setPreviewSize() method.

Does this paragraph specify what I need to do or does it pertain to something else? In any case, does anyone have any code snippet for how I would go about setting the size? say I want a square image, how would I specify it so that both the preview and the final image are both squares?

Right now my surfaceChanged method is as follows

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    if (mCamera != null) {
        try {
            mCamera.setPreviewDisplay(holder);
            if (mIsCapturing) {
                mCamera.startPreview();
            }
        } catch (IOException e) {
            Toast.makeText(CameraActivity.this, "Unable to start camera preview.", Toast.LENGTH_LONG).show();
        }
    }
}

Thanks for helping.

Also, in case it's important, my layout is

<FrameLayout
    android:id="@+id/camera_frame"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <ImageView
        android:id="@+id/camera_image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <SurfaceView
        android:id="@+id/preview_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>


Solution 1:[1]

Camera.Parameters

Parameters parameters = camera.getParameters();  

for (Camera.Size previewSize: camera.getParameters().getSupportedPreviewSizes()) 
{
     // if the size is suitable for you, use it and exit the loop.
     parameters.setPreviewSize(previewSize.width, previewSize.height);
     break;
}

camera.setParameters(parameters);
camera.startPreview();

as for a square preview and final image, how I do it is hide/block part of the preview using other views to make it squared, and cut the bitmap accordingly when saving the taken image.

Not pretty, but so far I've yet to find a better solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1