●縦向きの撮影に対応する
andoroidのカメラは基本横向きでの撮影が前提みたいです。
スマートな方法がほかにあれば、教えてほしいですが、自分は以下のようにしました。
1. カメラ用のアクティビティは横向き固定にする。
AndroidManifest.xmlで、以下のように指定しておきます。
こうすれば、端末をグルグル回しても勝手に画面作り直しになりません。
^^^^^^^^^^
2. 端末回転時のイベントを補足する。
端末が縦になって撮影された場合は、後で画像を回転させる必要があるので、自分で回転時のイベントを補足する必要があります。
以下のようなクラスを、カメラ用のアクティビティクラス内に作ります。
private class MyOrientationEventListener extends OrientationEventListener{
private int orientation = OrientationEventListener.ORIENTATION_UNKNOWN;
public MyOrientationEventListener(Context context, int rate) {
super(context, rate);
}
@Override
public void onOrientationChanged(int orientation) {
int new_orientation = 0;
if ( OrientationEventListener.ORIENTATION_UNKNOWN == orientation ){
return;
}
if ( orientation >= 315 || ( 0 <= orientation && 45 >= orientation ) ){
new_orientation = Configuration.ORIENTATION_PORTRAIT;
}else{
new_orientation = Configuration.ORIENTATION_LANDSCAPE;
}
if ( this.orientation != new_orientation ){
this.orientation = new_orientation;
rotate( this.orientation );
}
}
}
カメラ撮影用のアクティビティのonCreate内で、MyOrientationEventListenerを作成します。
oelは、クラスのメンバ変数として定義して下さい。(他のメソッド内でも参照するので)
oel = new MyOrientationEventListener(this, SensorManager.SENSOR_DELAY_UI);
oel.enable();
onPause内で、センサーを一旦とめます。
oel.disable();
onRestart内で、センサーを再開します。
oel.enable();
で、MyOrientationEventListener.onOrientationChangedから、端末の向きが変わった時に呼びしているrotateというメソッドをカメラ撮影用のアクティビティに実装します。
ここで、現在の向きをアクティビティ内の変数に保持しておきます。(撮影後に参照するため)
public void onOrientationChanged(int orientation) {
this.orientation = orientation;
}
ここまでで、内部的に端末の向きをリアルタイムで保持する仕組みができました。
3. 撮影後に、端末が縦向きの場合は画像を回転させる。
public void onPictureTaken(byte[] arg0, Camera arg1) {
if ( Configuration.ORIENTATION_LANDSCAPE != this.orientation ){ // 画面が縦向きの場合
// 撮影画像のデータからbitmapを作成する
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeByteArray(w, 0, w.length, opts);
// 画像を回転させる
Matrix matrix = new Matrix();
matrix.postRotate(90.0f);
bitmap_rotate = Bitmap.createBitmap(
bitmap, 0, 0,
bitmap.getWidth(),
bitmap.getHeight(),
matrix, true);
bitmap.recycle();
}