↑クリックして拡大
↑クリックして拡大
↑クリックして拡大
↑クリックして拡大

頭痛が減ったので共有です!

rebuild.fmを応援しています!

HOME > カメラで写真をとる(#1)

カメラで写真をとる(#1)

iPhoneのカメラを利用して撮影します。
(1回目は背面カメラを起動してフォーカスを当てるところまでを説明します)

参考(英語): Taking control of the iPhone camera in iOS 8 with Swift (Part 1)

AVCaptureDeviceで利用できるカメラを確認する


//利用できるカメラを確認する
import AVFoundation

 let captureSession = AVCaptureSession();
captureSession.sessionPreset = AVCaptureSessionPresetLow;
 let devices = AVCaptureDevice.devices();
 println(devices);

こんな感じで出力されます。(私のiPhone5Sの場合)


[AVCaptureFigVideoDevice: 0x156d19200 
[Back Camera][com.apple.avfoundation.avcapturedevice.built-in_video:0],
AVCaptureFigVideoDevice: 0x156d1c6c0
[Front Camera][com.apple.avfoundation.avcapturedevice.built-in_video:1],
AVCaptureFigAudioDevice: 0x170873d00
[iPhone マイク][com.apple.avfoundation.avcapturedevice.built-in_audio:0]]

AVCaptureVideoPreviewLayerカメラ画像を表示する


    import AVFoundation


    let captureSession = AVCaptureSession()
    var previewLayer : AVCaptureVideoPreviewLayer?
    var captureDevice : AVCaptureDevice?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
        let devices = AVCaptureDevice.devices()
        for device in devices {
            if (device.hasMediaType(AVMediaTypeVideo)) {
                // 背面カメラあるかどうか。ここを調整して全面カメラにしたりもできる
                if(device.position == AVCaptureDevicePosition.Back) {
                    captureDevice = device as? AVCaptureDevice
                    if captureDevice != nil {
                        println("背面カメラ発見しました。")
                        beginCamera()
                    }
                }
            }
        }
        
    }
    
    
    //カメラ設定
    func configureDevice() {
        if let device = captureDevice {
            device.lockForConfiguration(nil)
            device.focusMode = .Locked
            device.unlockForConfiguration()
        }
        
    }
    
    //カメラ開始!
    func beginCamera() {
        
        configureDevice()
        var err : NSError? = nil
        captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
        
        if err != nil {
            println("エラー: \(err?.localizedDescription)")
        }
        
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.view.layer.addSublayer(previewLayer)
        previewLayer?.frame = self.view.layer.frame
        captureSession.startRunning()
    }

カメラをタッチ動作でフォーカスさせる

以下コードを上記に追加します。overrideなのでそのまま関数を追加するだけ


    //フォーカス!
    func focusTo(value : Float) {
        if let device = captureDevice {
            if(device.lockForConfiguration(nil)) {
                device.setFocusModeLockedWithLensPosition(value, completionHandler: { (time) -> Void in
                    //
                })
                device.unlockForConfiguration()
            }
        }
    }
    
    //画面にタッチ
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        var anyTouch = touches.anyObject() as UITouch
        var touchPercent = anyTouch.locationInView(self.view).x / screenWidth
        focusTo(Float(touchPercent))
    }
    
    //タッチして移動
    override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
        var anyTouch = touches.anyObject() as UITouch
        var touchPercent = anyTouch.locationInView(self.view).x / screenWidth
        focusTo(Float(touchPercent))
    }

カメラ画像撮影は次の投稿で対応してまいります

↓こんな記事もありますよ!


2021-05-14 14:21:41

WatchOSのwatchconnectivityのFiletransferの落とし穴。と、避け方。

AppleWatch 実機だと成功するんだけど、シュミレーターだと失敗するという、、、 昔作成してた時は成功してたのになーと思って調べると、どうやら昔は成功してたみたい。watchOS6以降は...

2021-05-06 14:04:37

LINEのアニメーションスタンプ制作の落とし穴、、、失敗談

ゴールデンウィークにLINEスタンプを作成してみました。 作り切って申請も通したんですが、意図したアニメーションと違う、、、、 LINEクリエーターの画面だと、アニメーションのプレビュー...

2021-05-01 18:05:35

久しぶりのAdmobをobjective-cに実装。コンパイルエラーだらけ。バーミッション不具合でエミュレータにインスコできない。

忘れないようにメモ エミュレータにアプリをインストールする際にパーミッション系のエラーがでた時、また、iphone実機にインストールする際にも権限系のエラーが出る場合。 ターゲット→ex...
このエントリーをはてなブックマークに追加
右側のFacebookのLikeをクリック頂けると記事更新の際に通知されますので宜しければご利用下さい!