SurfaceView 自定義相機開發
Surfaceview 自定義相機,支援解析度修改,開關閃光燈,可以切換前後攝像頭,拍攝完成存為圖片,先上效果圖:
MainActicity.java
private Camera camera;
private boolean preview = false;
private ImageView change, takephoto,flash;
private int cameraPosition = 0;
private SurfaceHolder holder;
private ImageView imageView;
private LinearLayout ll_view;
int picWidth = 1920;
int picHeight = 1080;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 拍照過程螢幕一直處於高亮
setContentView(R.layout.activity_main);
initView();
ll_view.getBackground().setAlpha(80);
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
holder = surfaceView.getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//holder.setFixedSize(1080, 1920);
holder.addCallback(new SurfaceViewCallback());
takephoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
camera.autoFocus(new AutoFocusCallback() {// 自動對焦
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
camera.takePicture(null, null, jpeg);// 將拍攝到的照片給自定義的物件
}
}
});
}
});
change.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int cameraCount = 0;
CameraInfo cameraInfo = new CameraInfo();
cameraCount = Camera.getNumberOfCameras();// 得到攝像頭的個數
for (int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, cameraInfo);// 得到每一個攝像頭的資訊
if (cameraPosition == 0) {
// 現在是後置,變更為前置
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {// 代表攝像頭的方位,CAMERA_FACING_FRONT前置 // CAMERA_FACING_BACK後置
camera.stopPreview();// 停掉原來攝像頭的預覽
camera.release();// 釋放資源
camera = null;// 取消原來攝像頭
camera = Camera.open(i);// 開啟當前選中的攝像頭
try {
camera.setPreviewDisplay(holder);// 通過surfaceview顯示取景畫面
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getWH(camera);
setCameraDisplayOrientation(MainActicity.this,cameraPosition, camera,270);
camera.startPreview();// 開始預覽
cameraPosition = 1;
break;
}
} else {
// 現在是前置, 變更為後置
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {// 代表攝像頭的方位,CAMERA_FACING_FRONT前置 // CAMERA_FACING_BACK後置
camera.stopPreview();// 停掉原來攝像頭的預覽
camera.release();// 釋放資源
camera = null;// 取消原來攝像頭
camera = Camera.open(i);// 開啟當前選中的攝像頭
try {
camera.setPreviewDisplay(holder);// 通過surfaceview顯示取景畫面
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getWH(camera);
setCameraDisplayOrientation(MainActicity.this,cameraPosition, camera,0);
camera.startPreview();// 開始預覽
cameraPosition = 0;
break;
}
}
}
}
});
flash.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setFlashMode();
}
});
}