5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift 動画撮影をlandscape(横向き)で

Posted at

#AVCaptureMovieFileOutputの設定
まず, ファイル出力の設定時点で,向きを変更可能にします。(デフォルトは変更不可)

captureSession.addOutput(videoFileOutput)
let videoDataOuputConnection = videoFileOutput.connection(with: .video)
videoFileOutput.setRecordsVideoOrientationAndMirroringChangesAsMetadataTrack(true, for: videoDataOuputConnection!)

録画開始時にファイル出力の向きをデバイスの向きに合わせます。

let videoDataOuputConnection = videoFileOutput.connection(with: .video)
let orientation = UIDevice.current.orientation
videoDataOuputConnection!.videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue)!

参考:
How to record landscape video in a portrait application? (Swift 2, iPhone)

#表示映像の設定

回転した際に向きを取得します。

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    coordinator.animateAlongsideTransition(
        nil,
        completion: {(UIViewControllerTransitionCoordinatorContext) in
            //画面の回転後に向きを教える。
            if let orientation = self.convertUIOrientation2VideoOrientation({return UIApplication.sharedApplication().statusBarOrientation}) {
                videoPreviewLayer?.connection.videoOrientation = orientation
            }
        }
    )
}


func convertUIOrientation2VideoOrientation(f: () -> UIInterfaceOrientation) -> AVCaptureVideoOrientation? {
    let v = f()
    switch v {
        case UIInterfaceOrientation.Unknown:
            return nil
        default:
            return ([
                UIInterfaceOrientation.Portrait: AVCaptureVideoOrientation.Portrait,
                UIInterfaceOrientation.PortraitUpsideDown: AVCaptureVideoOrientation.PortraitUpsideDown,
                UIInterfaceOrientation.LandscapeLeft: AVCaptureVideoOrientation.LandscapeLeft,
                UIInterfaceOrientation.LandscapeRight: AVCaptureVideoOrientation.LandscapeRight
            ])[v]
    }
}

参考:
Swift - iOSでビデオカメラを使用時、端末の向きに対応

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?