手机镜子


参考连接:http://blog.csdn.net/wwj_748/article/details/8927784

首先手机必须具备前置摄像头。

找到前置摄像头的id:

private int findFrontCamera() {
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras(); // get cameras number
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return camIdx;
}
}
return -1;
}

设置回调函数:

private final class SurfaceCallback implements Callback {

// 拍照状态变化时调用该方法
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
parameters = camera.getParameters(); // 获取各项参数
parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
parameters.setPreviewSize(width, height); // 设置预览大小
parameters.setPreviewFrameRate(5); // 设置每秒显示4帧
parameters.setPictureSize(width, height); // 设置保存的图片尺寸
parameters.setJpegQuality(80); // 设置照片质量
}

// 开始拍照时调用该方法
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (cameraId != -1) {
camera = Camera.open(cameraId); // 打开摄像头
camera.setPreviewDisplay(holder); // 设置用于显示拍照影像的SurfaceHolder对象
camera.setDisplayOrientation(90);
camera.startPreview(); // 开始预览
}
} catch (Exception e) {
e.printStackTrace();
}

}

// 停止拍照时调用该方法
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.release(); // 释放照相机
camera = null;
}
}
}


设置参数,开启预览

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mirror);

cameraId = findFrontCamera();
if (cameraId == -1) {
Toast.makeText(this, "对不起,手机没有前置摄像头!", Toast.LENGTH_SHORT).show();
this.finish();
} else {
SurfaceView surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// surfaceView.getHolder().setFixedSize(1, 700); // 设置Surface分辨率
surfaceView.getHolder().setSizeFromLayout();
surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮
surfaceView.getHolder().addCallback(new SurfaceCallback());// 为SurfaceView的句柄添加一个回调函数
}
}

别忘了设置权限:<uses-permission android:name="android.permission.CAMERA" />

你可能感兴趣的:(android)