Skip to content

Instantly share code, notes, and snippets.

@rmzaki
Created September 27, 2016 13:47
Show Gist options
  • Save rmzaki/b420c287b699b61ffec0203701fb13f9 to your computer and use it in GitHub Desktop.
Save rmzaki/b420c287b699b61ffec0203701fb13f9 to your computer and use it in GitHub Desktop.
Xcode7.3.1でカメラの実装。
import UIKit
import AVFoundation
class ViewController: UIViewController {
// セッション.
var mySession : AVCaptureSession!
// デバイス.
var myDevice : AVCaptureDevice!
// 画像のアウトプット.
var myImageOutput : AVCaptureStillImageOutput!
override func viewDidLoad() {
super.viewDidLoad()
// セッションの作成.
mySession = AVCaptureSession()
// デバイス一覧の取得.
let devices = AVCaptureDevice.devices()
// バックカメラをmyDeviceに格納.
for device in devices{
if(device.position == AVCaptureDevicePosition.Back){
myDevice = device as! AVCaptureDevice
}
}
// バックカメラからVideoInputを取得.
do {
let videoInput = try AVCaptureDeviceInput(device: myDevice)
// セッションに追加.
mySession.addInput(videoInput)
// 出力先を生成.
myImageOutput = AVCaptureStillImageOutput()
// セッションに追加.
mySession.addOutput(myImageOutput)
// 画像を表示するレイヤーを生成.
// let myVideoLayer : AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.layerWithSession(mySession) as AVCaptureVideoPreviewLayer
let myVideoLayer = AVCaptureVideoPreviewLayer(session: mySession)
myVideoLayer.frame = self.view.bounds
myVideoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
// Viewに追加.
self.view.layer.addSublayer(myVideoLayer)
// セッション開始.
mySession.startRunning()
} catch {
// NSError以外のエラーが発生したとき
print("videoInputでエラー")
}
// UIボタンを作成.
let myButton = UIButton(frame: CGRectMake(0,0,120,50))
myButton.backgroundColor = UIColor.redColor();
myButton.layer.masksToBounds = true
myButton.setTitle("撮影", forState: .Normal)
myButton.layer.cornerRadius = 20.0
myButton.layer.position = CGPoint(x: self.view.bounds.width/2, y:self.view.bounds.height-50)
myButton.addTarget(self, action: #selector(ViewController.onClickMyButton(_:)), forControlEvents: .TouchUpInside)
// UIボタンをViewに追加.
self.view.addSubview(myButton);
}
// ボタンイベント.
func onClickMyButton(sender: UIButton){
// ビデオ出力に接続.
let myVideoConnection = myImageOutput.connectionWithMediaType(AVMediaTypeVideo)
// 接続から画像を取得.
self.myImageOutput.captureStillImageAsynchronouslyFromConnection(myVideoConnection, completionHandler: { (imageDataBuffer, error) -> Void in
// 取得したImageのDataBufferをJpegに変換.
let myImageData : NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataBuffer)
// JpegからUIIMageを作成.
let myImage : UIImage = UIImage(data: myImageData)!
// アルバムに追加.
UIImageWriteToSavedPhotosAlbum(myImage, self, nil, nil)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment