第一步: AndroidManifest.xml 在Activity添加以下一個屬性
android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="sensor",為的是能夠橫豎屏切換不用再次調用onCreate方法,直接調用onConfigurationChanged方法。screenSize是兼容4.0系統的才可以生效,否則方法沒效。
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="sensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
第二步,解決豎屏拍照后保存圖片會旋轉90度的問題。這里我會在onConfigurationChanged方法進行判斷當前是橫拍還是豎拍,然后在調用相機拍照后,在保存圖片的方法里,進行豎拍的照片90度旋轉。
PictureCallback jpeg = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // TODO Auto-generated method stub Bitmap bMap; try {// 獲得圖片 bMap = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap bMapRotate; if (takeType != 0) { //堅拍 Matrix matrix = new Matrix(); matrix.reset(); matrix.postRotate(90); bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), matrix, true); bMap = bMapRotate; } // Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); File file = new File(filePath); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);//將圖片壓縮到流中 bos.flush();//輸出 bos.close();//關閉 }catch(Exception e) { e.printStackTrace(); } } };
關鍵代碼是以上。
當用豎拍轉橫拍,還是橫拍轉豎拍,都要先在surfaceChanged方法,停止預覽相機,重新設置下攝像頭就不會再出現90度旋轉。