Android Camera Preview Stretched

133,528

Solution 1

I'm using this method -> based on API Demos to get my Preview Size:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> 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;
    }

As you can see you have to input width and height of your screen. This method will calculate screen ratio based on those values and then from the list of supportedPreviewSizes it will choose the best for you from avaliable ones. Get your supportedPreviewSize list in place where Camera object isn't null by using

mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();

And then on in onMeasure you can get your optimal previewSize like that:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes != null) {
           mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }
    }

And then (in my code in surfaceChanged method, like I said I'm using API Demos structure of CameraActivity code, you can generate it in Eclipse):

Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();

And one hint for you, because I did almost the same app like you. Good practice for Camera Activity is to hide StatusBar. Applications like Instagram are doing it. It reduces your screen height value and change your ratio value. It is possible to get strange Preview Sizes on some devices (your SurfaceView will be cut a little)


And to answer your question, how to check if your preview ratio is correct? Then get height and width of parameters that you set in:

mCamera.setParameters(parameters);

your set ratio is equal to height/width. If you want camera to look good on your screen then height/width ratio of parameters that you set to camera must be the same as height(minus status bar)/width ratio of your screen.

Solution 2

F1Sher's solution is nice but sometimes doesn't work. Particularly, when your surfaceView doesn't cover whole screen. In this case you need to override onMeasure() method. I have copied my code here for your reference.

Since I measured surfaceView based on width then I have little bit white gap at the end of my screen that I filled it by design. You are able to fix this issue if you keep height and increase width by multiply it to ratio. However, it will squish surfaceView slightly.

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "CameraPreview";

    private Context mContext;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private List<Camera.Size> mSupportedPreviewSizes;
    private Camera.Size mPreviewSize;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mContext = context;
        mCamera = camera;

        // supported preview sizes
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        for(Camera.Size str: mSupportedPreviewSizes)
                Log.e(TAG, str.width + "/" + str.height);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // empty. surfaceChanged will take care of stuff
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + h);
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.
        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or reformatting changes here
        // start preview with new settings
        try {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }

        if (mPreviewSize!=null) {
            float ratio;
            if(mPreviewSize.height >= mPreviewSize.width)
                ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
            else
                ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;

            // One of these methods should be used, second method squishes preview slightly
            setMeasuredDimension(width, (int) (width * ratio));
  //        setMeasuredDimension((int) (width * ratio), height);
        }
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> 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.height / size.width;
            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;
    }
}

Solution 3

NOTE: MY SOLUTION IS A CONTINUATION OF HESAM'S SOLUTION: https://stackoverflow.com/a/22758359/1718734

What I address: Hesam's said there is a little white space that may appear on some phones, like this:

NOTE: Although the aspect ratio is correct, the camera does not fill in the whole screen.

Hesam suggested a second solution, but that squishes the preview. And on some devices, it heavily distorts.

So how do we fix this problem. It is simple...by multiplying the aspect ratios till it fills in the screen. I have noticed, several popular apps such as Snapchat, WhatsApp, etc works the same way.

All you have to do is add this to the onMeasure method:

float camHeight = (int) (width * ratio);
    float newCamHeight;
    float newHeightRatio;

    if (camHeight < height) {
        newHeightRatio = (float) height / (float) mPreviewSize.height;
        newCamHeight = (newHeightRatio * camHeight);
        Log.e(TAG, camHeight + " " + height + " " + mPreviewSize.height + " " + newHeightRatio + " " + newCamHeight);
        setMeasuredDimension((int) (width * newHeightRatio), (int) newCamHeight);
        Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | H_ratio - " + newHeightRatio + " | A_width - " + (width * newHeightRatio) + " | A_height - " + newCamHeight);
    } else {
        newCamHeight = camHeight;
        setMeasuredDimension(width, (int) newCamHeight);
        Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | A_width - " + (width) + " | A_height - " + newCamHeight);
    }

This will calculate the screen height and gets the ratio of the screen height and the mPreviewSize height. Then it multiplies the camera's width and height by the new height ratio and the set the measured dimension accordingly.

enter image description here

And the next thing you know, you end up with this :D

enter image description here

This also works well with he front camera. I believe this is the best way to go about this. Now the only thing left for my app is to save the preview itself upon clicking on "Capture." But ya, this is it.

Solution 4

OK, so I think there is no sufficient answer for general camera preview stretching problem. Or at least I didn't find one. My app also suffered this stretching syndrome and it took me a while to puzzle together a solution from all the user answers on this portal and internet.

I tried @Hesam's solution but it didn't work and left my camera preview majorly distorted.

First I show the code of my solution (the important parts of the code) and then I explain why I took those steps. There is room for performance modifications.

Main activity xml layout:

<RelativeLayout 
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
</RelativeLayout>

Camera Preview:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder prHolder;
private Camera prCamera;
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;

@SuppressWarnings("deprecation")
public YoCameraPreview(Context context, Camera camera) {
    super(context);
    prCamera = camera;

    prSupportedPreviewSizes = prCamera.getParameters().getSupportedPreviewSizes();

    prHolder = getHolder();
    prHolder.addCallback(this);
    prHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        prCamera.setPreviewDisplay(holder);
        prCamera.startPreview();
    } catch (IOException e) {
        Log.d("Yologram", "Error setting camera preview: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if (prHolder.getSurface() == null){
      return;
    }

    try {
        prCamera.stopPreview();
    } catch (Exception e){
    }

    try {
        Camera.Parameters parameters = prCamera.getParameters();
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);

        prCamera.setParameters(parameters);
        prCamera.setPreviewDisplay(prHolder);
        prCamera.startPreview();

    } catch (Exception e){
        Log.d("Yologram", "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    setMeasuredDimension(width, height);

    if (prSupportedPreviewSizes != null) {
        prPreviewSize = 
            getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
    }    
}

public Camera.Size getOptimalPreviewSize(List<Camera.Size> 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;
}
}

Main activity:

public class MainActivity extends Activity {

...

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_main);

        maCamera = getCameraInstance();

        maLayoutPreview = (FrameLayout) findViewById(R.id.camera_preview);

        maPreview = new CameraPreview(this, maCamera);

        Point displayDim = getDisplayWH();
        Point layoutPreviewDim = calcCamPrevDimensions(displayDim, 
                maPreview.getOptimalPreviewSize(maPreview.prSupportedPreviewSizes, 
                    displayDim.x, displayDim.y));
        if (layoutPreviewDim != null) {
            RelativeLayout.LayoutParams layoutPreviewParams = 
                (RelativeLayout.LayoutParams) maLayoutPreview.getLayoutParams();
            layoutPreviewParams.width = layoutPreviewDim.x;
            layoutPreviewParams.height = layoutPreviewDim.y;
            layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            maLayoutPreview.setLayoutParams(layoutPreviewParams);
        }
        maLayoutPreview.addView(maPreview);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Point getDisplayWH() {

    Display display = this.getWindowManager().getDefaultDisplay();
    Point displayWH = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(displayWH);
        return displayWH;
    }
    displayWH.set(display.getWidth(), display.getHeight());
    return displayWH;
}

private Point calcCamPrevDimensions(Point disDim, Camera.Size camDim) {

    Point displayDim = disDim;
    Camera.Size cameraDim = camDim;

    double widthRatio = (double) displayDim.x / cameraDim.width;
    double heightRatio = (double) displayDim.y / cameraDim.height;

    // use ">" to zoom preview full screen
    if (widthRatio < heightRatio) {
        Point calcDimensions = new Point();
        calcDimensions.x = displayDim.x;
        calcDimensions.y = (displayDim.x * cameraDim.height) / cameraDim.width;
        return calcDimensions;
    }
    // use "<" to zoom preview full screen
    if (widthRatio > heightRatio) { 
        Point calcDimensions = new Point();
        calcDimensions.x = (displayDim.y * cameraDim.width) / cameraDim.height;
        calcDimensions.y = displayDim.y;
        return calcDimensions;
    }
    return null;
}   
}

My commentary:

The point of all this is, that although you calculate the optimal camera size in getOptimalPreviewSize() you only pick the closest ratio to fit your screen. So unless the ratio is exactly the same the preview will stretch.

Why will it stretch? Because your FrameLayout camera preview is set in layout.xml to match_parent in width and height. So that is why the preview will stretch to full screen.

What needs to be done is to set camera preview layout width and height to match the chosen camera size ratio, so the preview keeps its aspect ratio and won't distort.

I tried to use the CameraPreview class to do all the calculations and layout changes, but I couldn't figure it out. I tried to apply this solution, but SurfaceView doesn't recognize getChildCount () or getChildAt (int index). I think, I got it working eventually with a reference to maLayoutPreview, but it was misbehaving and applied the set ratio to my whole app and it did so after first picture was taken. So I let it go and moved the layout modifications to the MainActivity.

In CameraPreview I changed prSupportedPreviewSizes and getOptimalPreviewSize() to public so I can use it in MainActivity. Then I needed the display dimensions (minus the navigation/status bar if there is one) and chosen optimal camera size. I tried to get the RelativeLayout (or FrameLayout) size instead of display size, but it was returning zero value. This solution didn't work for me. The layout got it's value after onWindowFocusChanged (checked in the log).

So I have my methods for calculating the layout dimensions to match the aspect ratio of chosen camera size. Now you just need to set LayoutParams of your camera preview layout. Change the width, height and center it in parent.

There are two choices how to calculate the preview dimensions. Either you want it to fit the screen with black bars (if windowBackground is set to null) on the sides or top/bottom. Or you want the preview zoomed to full screen. I left comment with more information in calcCamPrevDimensions().

Solution 5

Hi the getOptimalPreview() that is here didn't worked for me so I want to share my version:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    if (sizes==null) return null;

    Camera.Size optimalSize = null;
    double ratio = (double)h/w;
    double minDiff = Double.MAX_VALUE;
    double newDiff;
    for (Camera.Size size : sizes) {
        newDiff = Math.abs((double)size.width/size.height - ratio);
        if (newDiff < minDiff) {
            optimalSize = size;
            minDiff = newDiff;
        }
    }
    return optimalSize;
}
Share:
133,528
scientiffic
Author by

scientiffic

Updated on July 10, 2022

Comments

  • scientiffic
    scientiffic almost 2 years

    I've been working on making my custom camera activity on Android, but when rotating the camera, the aspect ratio of the surface view gets messed up.

    In my oncreate for the activity, I set the framelayout which holds the surface view that displays the camera's parameters.

    //FrameLayout that will hold the camera preview
            FrameLayout previewHolder = (FrameLayout) findViewById(R.id.camerapreview);
    
            //Setting camera's preview size to the best preview size
            Size optimalSize = null;
            camera = getCameraInstance();
            double aspectRatio = 0;
            if(camera != null){
                //Setting the camera's aspect ratio
                Camera.Parameters parameters = camera.getParameters();
                List<Size> sizes = parameters.getSupportedPreviewSizes();
                optimalSize = CameraPreview.getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
                aspectRatio = (float)optimalSize.width/optimalSize.height;
            }
    
            if(optimalSize!= null){
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(getResources().getDisplayMetrics().widthPixels*aspectRatio));
                previewHolder.setLayoutParams(params);
                LayoutParams surfaceParams = new LayoutParams(LayoutParams.MATCH_PARENT, (int)(getResources().getDisplayMetrics().widthPixels*aspectRatio));
                cameraPreview.setLayoutParams(surfaceParams);
    
            }
    
            cameraPreview.setCamera(camera);
    
            //Adding the preview to the holder
            previewHolder.addView(cameraPreview);
    

    Then, in the Surface view I set the camera's parameters to be displayed

    public void setCamera(Camera camera) {
            if (mCamera == camera) { return; }
    
            mCamera = camera;
    
            if (mCamera != null) {
                requestLayout();
    
                try {
                    mCamera.setPreviewDisplay(mHolder);
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
    
                if(mCamera != null){
                    //Setting the camera's aspect ratio
                    Camera.Parameters parameters = mCamera.getParameters();
                    List<Size> sizes = parameters.getSupportedPreviewSizes();
                    Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
    
                    parameters.setPreviewSize(optimalSize.width, optimalSize.height);
                    mCamera.setParameters(parameters);
                }
    
                /*
                  Important: Call startPreview() to start updating the preview surface. Preview must 
                  be started before you can take a picture.
                  */
                mCamera.startPreview();
            }
    
        }
    

    enter image description here

    You can see that the LEGO man grows taller and skinnier when the phone is rotated:

    How can I ensure that the aspect ratio for my camera view is correct?

  • scientiffic
    scientiffic over 10 years
    is this different than setting my camera view's parameter this way (which I'm currently doing): parameters.setPreviewSize(optimalSize.width, optimalSize.height); mCamera.setParameters(parameters);
  • phyzalis
    phyzalis over 10 years
    Just one question : I see your are using 2 different computed ratio : double targetRatio=(double)h / w and double ratio = (double) size.width / size.height. The first one is the height divided by the width and the other is the opposite, the width divided by the height. Should they not be the same computation ?
  • F1sher
    F1sher over 10 years
    It doesn't matter because list of sizes takes into consideration every possibility for example: you will find something like 480x680, but sooner or later there will be 680x480 (for landscape), so you just have to go over that list and find one that matches your needs. You will find it sooner or later.
  • Houcine
    Houcine about 10 years
    this should be the correct answer, it handles the case when the camera's preview is not covering the whole screen. +1 .
  • fish40
    fish40 almost 10 years
    when I inflate in my activity application was closed <com.app.camera.CameraPreview android:id="@+id/camera_preview" android:layout_width="match_parent" android:layout_height="match_parent" />
  • Matt Logan
    Matt Logan almost 10 years
    Furthermore, if you want your pictures to be this size as well (as they probably should be), you have set the picture size with parameters.setPictureSize(mPreviewSize.width, mPreviewSize.height).
  • JaydeepW
    JaydeepW over 9 years
    You need to make some modifications though but I accept this as a solution. Up-voted.
  • FIXI
    FIXI over 9 years
    @F1sher, i always get null pointer exception parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); Can't find any solution.
  • Praveena
    Praveena over 9 years
    @F1sher If I am using fullscreen to preview then optimal preview size always will be screen resolution.. Please correct me if I am wrong here
  • fernio
    fernio about 9 years
    @phyzalis I agree with you. In fact, I had to make that correction for the code to work as expected.
  • Mitesh Shah
    Mitesh Shah almost 9 years
    I am using activity, and there is no onMeasure method in it. :( I know that i need a separate class which extends SurfaceView but then i get NullPointerException..
  • Matan Dahan
    Matan Dahan almost 9 years
    This works very good!! but it does not work properly in Landscape :/
  • Adnan Abdollah Zaki
    Adnan Abdollah Zaki almost 9 years
    hi @Hesam , can u explain more and show me about your Activity class , how you use this code .
  • Hesam
    Hesam almost 9 years
    Hi @adnan9011 , this tutorial might be helpful probably. airpair.com/android/android-camera-surface-view-fragment
  • Adnan Abdollah Zaki
    Adnan Abdollah Zaki almost 9 years
    @Hesam Kamalan , i write activity but not showing any thing in surfaceview . one thing is wrong
  • Wubbalubbadubdub
    Wubbalubbadubdub over 8 years
    Hello I'm dealing with the same problem , and your answer is quite clear . but my surface view is inside a Framelayout so I have created a customised view which extends FrmaLayout . I have done this to Override the onMeasure() method . But inside this method you wrote a methode resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec) . Can you please show me this method's functionality . @F1sher
  • F1sher
    F1sher over 8 years
    I haven't touched that code in 2 years or even more but if that helps you: gist.github.com/FisherHUB/ca209e4cb740b65b4ee6 and resolveSize is not my method, it's part of ViewGroup. developer.android.com/reference/android/view/ViewGroup.html
  • ono
    ono over 8 years
    the height and width needed to be switched in getOptimalPreviewSize for this to work for me. is this because the display orientation was set to 90? Otherwise, the ratio calculations weren't even close (target was 1.7 and camera ratios were less than 1)
  • karthik kolanji
    karthik kolanji about 8 years
    your code solved my 2 months empty black space problem :)
  • Shankar
    Shankar about 8 years
    camera showing blank(Black) screen. mPreview = new CameraPreviewNew(getActivity(), mCamera); topLayout.addView(mPreview); same code copy paste.
  • Neon Warge
    Neon Warge almost 8 years
    Did you just copy the code from here? java2s.com/Code/Android/Hardware/…
  • F1sher
    F1sher almost 8 years
    Hello, as I have written, I generated this code in Eclipse from provided Android solutions called API demos, few years ago.
  • Nitesh Khosla
    Nitesh Khosla almost 8 years
    camera move blink blur camera quality few seconds.Any solution
  • Makalele
    Makalele over 7 years
    It works, but in my case.. I have actionbar on the top so the white bar was smaller, however after adding your code my camera look zoomed in 40-50%. When switching to the front facing camera I basically cannot see my face looking straight (just a bit of hair), because of that high zoom.
  • G. Steigert
    G. Steigert about 7 years
    The Android doc says: When setting preview size, you must use values from getSupportedPreviewSizes(). Do not set arbitrary values in the setPreviewSize() method.
  • chinmish
    chinmish almost 7 years
    I am getting white screen when I follow your code. Any suggestion will be very helpful.
  • Kush Patel
    Kush Patel over 6 years
    @F1sher I am getting white screen when I followed your code. In onMeasure(int widthMeasureSpec, int heightMeasureSpec) method I always get width = 0 and height = 0;
  • Kush Patel
    Kush Patel over 6 years
    @Hesam I am getting white screen when I followed your code. In onMeasure(int widthMeasureSpec, int heightMeasureSpec) method I always get width = 0 and height = 0;
  • Kush Patel
    Kush Patel over 6 years
    @Yoosuf I am getting white screen when I followed your code. In onMeasure(int widthMeasureSpec, int heightMeasureSpec) method I always get width = 0 and height = 0;
  • Shujito
    Shujito about 6 years
    I didn't thought that adjusting the measured dimensions would fix it, works like a charm. In my case I took the preview parameters from the camera because I had it configured already.
  • Julius
    Julius almost 6 years
    mContext is not necessary in this case as the same value will be provided by getContext()
  • MohanRaj S
    MohanRaj S over 5 years
    it converts into a square camera, Given input is (1920x1080) after optimizing width and height it gave (1088x1088), My testing device is Samsung S6. May I know what is the reason. please share if u have any idea regarding this issue.
  • Timo Schuck
    Timo Schuck almost 5 years
    This solution doesn't fix it for me. However, just replacing the target high with int targetHeight = (int) ((double) h * targetRatio); works for me!!!
  • laim2003
    laim2003 over 4 years
    class Camera.Size is deprecated.
  • Richard
    Richard over 4 years
    This camera rotation will break ! Use the code on the android docs: developer.android.com/reference/android/hardware/…
  • Innocent
    Innocent over 3 years
    i need solution in kotlin if you have please send me
  • Vijay
    Vijay almost 3 years
    reason maybe, you are passing the same width and height.