解决Android相机竖屏预览的问题

来源:互联网 发布:2017好看的日剧 知乎 编辑:程序博客网 时间:2024/04/28 17:01

在AAndroidManifest.xml 中的<activity> </activity>设置屏幕方向为竖屏:

 android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation" >
Android开发文档中,设置预览方向的代码如下:

http://developer.android.com/intl/zh-cn/training/camera/cameradirect.html

public static void setCameraDisplayOrientation (Activity activity, int cameraId, android.hardware.Camera camera) {android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();android.hardware.Camera.getCameraInfo (cameraId , info);int rotation = activity.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-facingresult = ( info.orientation - degrees + 360) % 360;}camera.setDisplayOrientation (result);}


但是onPreviewFrame(byte[], Camera)中获取的 (JPEG pictures, or recorded videos )图像数据还是横屏的。所以如果使用SurfaceView来实现绘图显示,绘制在一个Canvas上,在画布上绘制时,需要将图片旋转90度,才能实现正确的竖屏显示。

下边是旋转图片的代码:

    private  Bitmap rotateImage(int angle,Bitmap bitmap) {          //旋转图片    Matrix matrix = new Matrix();          matrix.postRotate(angle);           // 创建新的图片          Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,                  bitmap.getWidth(), bitmap.getHeight(), matrix, true);                  return resizedBitmap;      }

后来我把设置预览方向的方法setCameraDisplayOrientation()去掉,仍然可以竖屏显示,原因是在使用画布绘制是,绘制的Bitmap已经旋转成竖屏的了。只是使用Canvas这种方式,把图片旋转后显示,效果不流畅,可能对每一帧使用matrix.postRotate(angle)进行旋转,耗时较大。希望有其他方法解决竖屏预览的问题!





0 0
原创粉丝点击