自定义Android相机应用程序,相机预览问题

时间:2013-07-10 17:12:16

标签: android android-camera surfaceview preview distortion

相机预览显示的是扭曲的图像,在纵向模式下会拉长,在横向时会变平。我已经用百万种技术调整了预览大小。然后我在某处阅读它必须是调整SurfaceView的大小。但到目前为止,我还没有找到合适的东西。

这是我的activity.java文件:

public class CameraActivity extends Activity {

private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout preview;
private static final String TAG = "CameraActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    if (checkCameraHardware(getBaseContext())){
        // Create an instance of Camera
        mCamera = getCameraInstance();
        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera, CameraActivity.this);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);

    }
}

/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
    if     (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
         Log.d(TAG, "Camera Available");
        return true;
    } else {
        Log.d(TAG, "No Camera Found");
        return false;
    }
}

/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
    Camera c = null;
    try {
        int i = Camera.getNumberOfCameras();
        releaseCamera(); //in case camera is being accessed by any other app.
        Log.d(TAG, "Number of Cameras "+i +"\n");
        c = Camera.open(); // attempt to get a Camera instance
        Log.d(TAG, "Camera Opened");
    }
    catch (Exception e){
         Log.d(TAG, "Camera Can't Be Accessed");
    }
    return c; // returns null if camera is unavailable
}


 @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseCamera(){
        if (mCamera != null){
            //mCamera.setPreviewCallback(null);
            mPreview.getHolder().removeCallback(mPreview);
            mCamera.release();        // release the camera for other applications
        }
    }

这是我的相机预览课程:

@SuppressLint("ViewConstructor")
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
private Size mPreviewSize; 

@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera, Activity activity) {
    super(context);
    mCamera = camera;
    // 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) {
    // The Surface has been created, now tell the camera where to draw the preview.

    try {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    } catch (IOException e) {
        Log.d(TAG, "Error setting camera preview: " + e.getMessage());
    }
}


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) {
    // 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
    Camera.Parameters parameters = mCamera.getParameters();
    List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();
    mPreviewSize = localSizes.get(0);
    Log.d(TAG, "Width " + mPreviewSize.width);
    Log.d(TAG, "Height " + mPreviewSize.height);

    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height );
    requestLayout();
    mCamera.setParameters(parameters);

    //start preview with new settings
    try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
    } catch (Exception e){
        Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}


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 = 0; break;
         case Surface.ROTATION_270: degrees = -90; 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);
    }


   }

这是我的activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:baselineAligned="false"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".CameraActivity" >

<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight = "1"
/>


</LinearLayout>

3 个答案:

答案 0 :(得分:1)

您的SurfaceView(或TextureView)必须与预览图片具有相同的宽高比,否则您将获得所描述的失真。

FWIW,您可能会发现使用my CWAC-Camera library很有用,{{3}}提供CameraFragment可以为您处理大量此类低级内容。不过,它仍在进行中。

答案 1 :(得分:1)

您可以找到相机预览宽度&amp;在onCreate中创建相机实例时的高度。然后,选择layout_widthlayout_height,使它们适合预览 FrameLayout并保留相机的纵横比。您可以使用FrameLayout.addView(View, LayoutParams)

答案 2 :(得分:0)

不确定是否有人仍然会阅读此内容,但我遇到了同样的问题并this answer修复了此问题。 我在这里复制代码以防万一(我也编辑它以匹配这个例子):

mCamera.Parameters parameters1 = mCamera.getParameters();
parameters1.setPreviewSize(getWidth(), getHeight());
mCamera.setParameters(parameters1);

在此之前添加以下行:

mCamera.startPreview();