开发者

Rotating a Camera SurfaceView to portrait

I have looked up a few posts on changing the orientation of the camera with a surface view, but I have taken my code from the examples at:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html

The function that provides the dimensions looks like this...

    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (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);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

My problem is that when I change the orientation of the device, the preview picture stays landscape. I tried setting the orientation of the camera but this resulted in very strange results. Does anyone know开发者_运维技巧 what I need to change to have this rotate properly?


The code to correctly adjust the camera preview orientation is a bit complex, since it has to take into account

  1. The relative orientation of the sensor and the device's 'natural' orientation (which is portrait for phones, landscape for tablets, typically)
  2. The current UI orientation of the device (portrait, landscape or the reverse of each)
  3. Whether the camera in question is the front or the back camera (since the front preview stream is mirrored horizontally)

The documentation for Camera.setDisplayOrientation has sample code on how to deal with this correctly. I'm reproducing it here:

public static void setCameraDisplayOrientation(Activity activity,
     int cameraId, android.hardware.Camera camera) {

   android.hardware.Camera.CameraInfo info = 
       new android.hardware.Camera.CameraInfo();

   android.hardware.Camera.getCameraInfo(cameraId, info);

   int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
   int degrees = 0;

   switch (rotation) {
       case Surface.ROTATION_0: degrees = 0; break;
       case Surface.ROTATION_90: degrees = 90; break;
       case Surface.ROTATION_180: degrees = 180; break;
       case Surface.ROTATION_270: degrees = 270; break;
   }

   int result;
   if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
       result = (info.orientation + degrees) % 360;
       result = (360 - result) % 360;  // compensate the mirror
   } else {  // back-facing
       result = (info.orientation - degrees + 360) % 360;
   }
   camera.setDisplayOrientation(result);
}

Call this after your UI has been drawn (onSurfaceChanged would work as an indicator) or the device UI rotates (onConfigurationChanged would work as an indicator).


I was able to solve the rotation problem by putting the following code in onSurfaceChanged():

    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
    }

    // make any resize, rotate or reformatting changes here
    if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {

        mCamera.setDisplayOrientation(90);

    } else {

        mCamera.setDisplayOrientation(0);

    }
    // start preview with new settings
    try {
        mCamera.setPreviewDisplay(mHolder);
        mCamera.startPreview();

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

BUT this created another problem, or better put, didn't solve a problem-while oriented correctly, the preview image still only took up the same amount of space that the landscape view did. I ended up just giving up and forcing landscape orientation with:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

in onCreate() and designed my layout for landscape. Best of luck, and I hope someone has an answer for this secondary problem!


Try this out, but I tried in Samsung Galaxy Tab

public void surfaceCreated(SurfaceHolder holder)
{
   // The Surface has been created, acquire the camera and tell it where to draw.
   mCamera = Camera.open();

   Parameters params = mCamera.getParameters();

   if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
   {
    params.set("orientation", "portrait");
    mCamera.setDisplayOrientation(90);
   }

    try
      {
      mCamera.setPreviewDisplay(holder);
      }
      catch (IOException exception)
      {
        mCamera.release();
        mCamera = null;
      }

}


I solved this issue by adding:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

To the onCreate event.


Please try this..

@Override
 public void surfaceChanged(SurfaceHolder holder,
                       int format, int width, int height)
{
// TODO Auto-generated method stub

if(previewing)
{
    camera.stopPreview();
    previewing = false;
}
 Camera.Parameters parameters = camera.getParameters();
      Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
   int or=cameraInfo.orientation;
     // You need to choose the most appropriate previewSize for your app
   // .... select one of previewSizes here
           /* parameters.setPreviewSize(previewSize.width, previewSize.height);*/
   if(display.getRotation() == Surface.ROTATION_0)
    {

    camera.setDisplayOrientation(90);
    or=90;
    }

    if(display.getRotation() == Surface.ROTATION_180)
    {
        camera.setDisplayOrientation(270);
    or=270;
    }
    if(display.getRotation() == Surface.ROTATION_270)
    {
        camera.setDisplayOrientation(180);
        or=180;
    }

  parameters.setRotation(or);

  camera.setParameters(parameters);
 try
{
        camera.setPreviewDisplay(cameraSurfaceHolder);
        camera.startPreview();
        previewing = true;
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


Well i Do this!

I have solved this issue in in this way in surfaceCreated() method

 public void surfaceCreated(SurfaceHolder holder) {
    try {

        camera = Camera.open();
    } catch (RuntimeException e) {
        System.err.println(e);
        return;
    }
    Camera.Parameters param;
    param = camera.getParameters();
    if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
    {
        param.set("orientation", "portrait");
        setCameraDisplayOrientation(this,1,camera);
    }
    camera.setParameters(param);

    try {
        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();
    } catch (Exception e) {
        System.err.println(e);
        return;
    }
}

add this method below

 public static void setCameraDisplayOrientation(Activity activity,
                                               int cameraId, android.hardware.Camera camera) {

    android.hardware.Camera.CameraInfo info =
            new android.hardware.Camera.CameraInfo();

    android.hardware.Camera.getCameraInfo(cameraId, info);

    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int degrees = 0;

    switch (rotation) {
        case Surface.ROTATION_0: degrees = 0; break;
        case Surface.ROTATION_90: degrees = 90; break;
        case Surface.ROTATION_180: degrees = 180; break;
        case Surface.ROTATION_270: degrees = 270; break;
    }

    int result;
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        result = (info.orientation + degrees) % 360;
        result = (360 - result) % 360;  // compensate the mirror
    } else {  // back-facing
        result = (info.orientation - degrees + 360) % 360;
    }
    camera.setDisplayOrientation(result);
}

3: Make sure you have added camera permiison to support for nougat in a activity before this activity calling dont call permission for camera in this activity because surfacecreated call as the activity created, and your permission will be pending to open camera


Only add this

mCamera.setDisplayOrientation(90);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜