[android] Camera Preview

카메라를 더 쉽게 쓸 수는 없는건가…

 

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraActivity extends Activity
{
  private static final int CAMERA_ID = 1;
  private Preview _preview;
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    _preview = new Preview(this);
    setContentView(_preview);
  }
  
  class Preview extends SurfaceView implements SurfaceHolder.Callback
  {
    private SurfaceHolder _holder;
    private Camera _camera;
    
    
    Preview(Context context)
    {
      super(context);
      
      _holder = getHolder();
      _holder.addCallback(this);
    }
    
    
    public void surfaceCreated(SurfaceHolder holder)
    {
      _camera = Camera.open(CAMERA_ID);
      try
      {
        _camera.setPreviewDisplay(holder);
      }
      catch (IOException exception)
      {
        _camera.release();
        _camera = null;
      }
    }
    
    
    public void surfaceDestroyed(SurfaceHolder holder)
    {
      _camera.stopPreview();
      _camera.release();
      _camera = null;
    }
    
    
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
      Camera.Parameters parameters = _camera.getParameters();
      Camera.Size bestSize = null;
      
      List<Camera.Size> sizeList = _camera.getParameters().getSupportedPreviewSizes();
      bestSize = sizeList.get(0);
      
      for (int i = 1; i < sizeList.size(); i++)
      {
        if ((sizeList.get(i).width * sizeList.get(i).height) > (bestSize.width * bestSize.height))
        {
          bestSize = sizeList.get(i);
        }
      }
      
      parameters.setPreviewSize(bestSize.width, bestSize.height);
      _camera.setParameters(parameters);
      
      CameraInfo info = new CameraInfo();
      Camera.getCameraInfo(CAMERA_ID, info);
      int rotation = 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);
      _camera.startPreview();
    }
  }