LoginSignup
14
11

More than 5 years have passed since last update.

カメラで撮影した画像の向きをデバイスに合わせる

Last updated at Posted at 2014-12-12

※画面向き設定をPortraitに固定して、デバイスを横などに向けて撮る時に使うものです。
画面向きを固定しない場合はAVCaptureVideoOrientationを対応させれば良いみたいです。

デバイスの向き取得と対応したUIImageOrientation

CMMotionManaferでデバイスの向きを取得して
画像を生成する際に回転させるためのUIImageOrientationを取得する。

var manager: CMMotionManager!
var photoOrientation: UIImageOrientation!

private func initMotion() {
    manager = CMMotionManager()
    manager.accelerometerUpdateInterval = 0.01;
    let handler:CMAccelerometerHandler = {(data:CMAccelerometerData!, error:NSError!) -> Void in
        let x = data.acceleration.x
        let y = data.acceleration.y
        let z = data.acceleration.z
        NSLog("x: %@%.2f", (x < 0 ? "-" : " "), fabs(x))
        NSLog("y: %@%.2f", (y < 0 ? "-" : " "), fabs(y))
        NSLog("z: %@%.2f", (z < 0 ? "-" : " "), fabs(z))
        self.photoOrientation = self.getOrientation(x, y: y)
    }
    manager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:handler)
}

private func getOrientation(x: Double, y: Double) -> UIImageOrientation {
    var orientation :UIImageOrientation!
    if (fabs(x) < 0.5) {
        if (y < 0) {
            // ホームボタン:下
            orientation = UIImageOrientation.Right
        } else {
            // ホームボタン:上
            orientation = UIImageOrientation.Left
        }
    } else {
        if (x < 0) {
            // ホームボタン:右
            orientation = UIImageOrientation.Up
        } else {
            // ホームボタン:左
            orientation = UIImageOrientation.Down
        }
    }
    return orientation
}

画像の回転

UIImageを回転させる

let result = UIImage(CGImage: image.CGImage, scale: 1.0, orientation: orientation)!

注意

CMMotionManagerはメソッド内にしかスコープのないオブジェクトに格納するとstartAccelerometerUpdatesなどで検知できない。
クラスにメンバ変数として持たせる必要がある。

14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11