Android实现手机摄像头的自动对焦
如何实现Android相机的自动对焦,而且是连续自动对焦的。当然直接调用系统相机就不用说了,那个很简单的。下面我们主要来看看如如何自己实现一个相机,并且实现自动连续对焦。
代码如下:
publicclassMainActivityextendsActivity{
privateSurfaceViewsurfaceView;
privateSurfaceHoldersurfaceHolder;
privatebooleanflag=false;
privateStringfileUrl="";
Cameracamera;
Camera.Parametersparameters;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView=(SurfaceView)findViewById(R.id.surfaceView1);
Buttonbutton=(Button)findViewById(R.id.takepicture);
surfaceHolder=surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.setKeepScreenOn(true);
surfaceView.setFocusable(true);
surfaceView.setBackgroundColor(TRIM_MEMORY_BACKGROUND);
surfaceHolder.addCallback(newCallback(){
@Override
publicvoidsurfaceDestroyed(SurfaceHolderholder){
//TODOAuto-generatedmethodstub
camera.stopPreview();
camera.release();
camera=null;
}
@Override
publicvoidsurfaceCreated(SurfaceHolderholder){
//TODOAuto-generatedmethodstub
if(null==camera){
camera=Camera.open();
try{
camera.setPreviewDisplay(surfaceHolder);
initCamera();
camera.startPreview();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
@Override
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,intheight){
//实现自动对焦
camera.autoFocus(newAutoFocusCallback(){
@Override
publicvoidonAutoFocus(booleansuccess,Cameracamera){
if(success){
initCamera();//实现相机的参数初始化
camera.cancelAutoFocus();//只有加上了这一句,才会自动对焦。
}
}
});
}
});
}
//相机参数的初始化设置
privatevoidinitCamera()
{
parameters=camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
//parameters.setPictureSize(surfaceView.getWidth(),surfaceView.getHeight());//部分定制手机,无法正常识别该方法。
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
setDispaly(parameters,camera);
camera.setParameters(parameters);
camera.startPreview();
camera.cancelAutoFocus();//2如果要实现连续的自动对焦,这一句必须加上
}
//控制图像的正确显示方向
privatevoidsetDispaly(Camera.Parametersparameters,Cameracamera)
{
if(Integer.parseInt(Build.VERSION.SDK)>=8){
setDisplayOrientation(camera,90);
}
else{
parameters.setRotation(90);
}
}
//实现的图像的正确显示
privatevoidsetDisplayOrientation(Cameracamera,inti){
MethoddownPolymorphic;
try{
downPolymorphic=camera.getClass().getMethod("setDisplayOrientation",newClass[]{int.class});
if(downPolymorphic!=null){
downPolymorphic.invoke(camera,newObject[]{i});
}
}
catch(Exceptione){
Log.e("Came_e","图像出错");
}
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。