近日来,一直学习Android Camera 的API, 希望自己可以订制一个Camera 应用.
经过学习和实践, 关于摄像头 横竖屏的问题,弄了很长时间,网上看了很多方法,都一一实践.这里做个总结.
首先安全打开摄像头,这里就不多说了
mCamera = Camera.open(id);
一. 设置preview 横竖屏
使用的方法是:
mCamera.setDisplayOrientation(int degrees);
横竖屏切换完整代码:
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Configuration mConfiguration = getResources().getConfiguration(); int ori = mConfiguration.orientation; if (ori == Configuration.ORIENTATION_LANDSCAPE){ mCamera.setDisplayOrientation(0); }else if (ori == Configuration.ORIENTATION_PORTRAIT){ mCamera.setDisplayOrientation(90); } //mCamera.setDisplayOrientation(90);//设置preview 90度 转 try { mCamera.setPreviewDisplay(mHolder); } catch (IOException e) { e.printStackTrace(); } mCamera.startPreview(); }
到此为止,只能使preview 正常, 但是录下的视频依然是-90显示. 下面来解决录下视频的问题:
使用方法:
mediaRecorder.setOrientationHint(90);
完整代码:
public void recordvideo(){ try { mCamera.unlock(); File videofile = new File(Environment.getExternalStorageDirectory() + "/test/", System.currentTimeMillis() + ".mp4"); mediaRecorder = new MediaRecorder(); mediaRecorder.setCamera(mCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); mediaRecorder.setOutputFile(videofile.getAbsolutePath()); mediaRecorder.setOrientationHint(90);//不改变preview,只对录下来的是视频起作用. mediaRecorder.prepare(); mediaRecorder.start(); Log.e(TAG,"START RECORDING"); }catch (Exception e){ Log.e("huashuo","can't record"); e.printStackTrace(); }
总结:
setDisplayOrientation, 改变设置preview
mediaRecorder.setOrientationHint(90);//不改变preview,只对录下来的是视频起作用.
当然,最简单的办法是在AndroidManifest.xml中配置android:screenOrientation="portrait", 然后设置mediaRecorder.setOrientationHint(90)
P.S 此方法在原生android4.4上测试通过.