Allan Jiang
Allan Jiang

Reputation: 11331

How to get Android Camera Preview ratio 1:1

I am trying to implement the a Android camera preview and want to have it display in 1:1 ratio (just like the Instagram camera).
I know how to deal with the preview frame size to be 1:1, but the camera output shows on the preview is squeezed. It looks like the live preview is still in 4:3 ratio but is squeezed to 1:1 frame. Is there a way to have the live preview also in 1:1 ratio?

I am not pasting any code here because I have tried many approach but all failed, nothing I can post...

Thank you

Upvotes: 2

Views: 8602

Answers (3)

Kosh
Kosh

Reputation: 6334

i know its an old question but here how i did it.

in your custom SurfaceView class add this

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}

this will square the preview but not the image taken. here comes the trick

on capture button you'll have to autoFocus the preview first and then immediately stopPreivew in this case you'll stop 'freeze' the preview and you can have the surfaceView inside of FrameLayout which its height set to wrap_content then you can save the cache view of that framelayout as bitmap and then save that bitmap.

Upvotes: 0

Alex Cohn
Alex Cohn

Reputation: 57173

As you have noticed, camera preview frames are 4:3. Often, you can also setPreviewSize() to have aspect ratio ~9:4 (e.g. 800x480). I have not encountered an Android device that will have a square among getSupportedPreviewSizes().

Your options to display a square preview are as follows: overlay the preview SurfaceView with non-transparent margins ontwo sides (effectively cropping the look). Or you could crop the image while displaying the TextureSurface through OpenGL. Or you could setPreviewCallbackWithBuffer(), crop the yuv frame to your desired size, and display it (prefferably, through OpenGL).

Upvotes: 7

Rajan
Rajan

Reputation: 1069

Try this

private void setCameraPreview_Frame()
{
    RelativeLayout rel_Camera_Preview = (RelativeLayout)findViewById(R.id.rel_Camera_Preview);
    int width = rel_Camera_Preview.getWidth();
    int height = rel_Camera_Preview.getHeight();

    if(width<height)
        height = width;
    else
        width = height;

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
    layoutParams.setMargins(10, 10, 10, 10);
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    camera_preview.setLayoutParams(layoutParams);
}

camera_preview is your FrameLayout that contains Camera Preview.

EDIT

And yes call this method like that

@Override
public void onWindowFocusChanged(boolean hasFocus) 
{
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus)
    {
        setCameraPreview_Frame();
    }
}

Upvotes: 0

Related Questions