Wilson Tang’s Blog

I am a slow walker, but I never walk backwards.

使用AVFoundation启动相机并保存

| Comments

效果图

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()

        for device in devices{
            if(device.position == AVCaptureDevicePosition.Back){
                myDevice = device as AVCaptureDevice
            }
        }

        let videoInput = AVCaptureDeviceInput.deviceInputWithDevice(myDevice, error: nil) as AVCaptureDeviceInput

        mySession.addInput(videoInput)

        myImageOutput = AVCaptureStillImageOutput()

        mySession.addOutput(myImageOutput)

        let myVideoLayer : AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.layerWithSession(mySession) as AVCaptureVideoPreviewLayer
        myVideoLayer.frame = self.view.bounds
        myVideoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        self.view.layer.addSublayer(myVideoLayer)

        mySession.startRunning()

        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: "onClickMyButton:", forControlEvents: .TouchUpInside)

        self.view.addSubview(myButton);
    }

    func onClickMyButton(sender: UIButton){
        let myVideoConnection = myImageOutput.connectionWithMediaType(AVMediaTypeVideo)
        self.myImageOutput.captureStillImageAsynchronouslyFromConnection(myVideoConnection, completionHandler: { (imageDataBuffer, error) -> Void in
            let myImageData : NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataBuffer)
            let myImage : UIImage = UIImage(data: myImageData)!
            UIImageWriteToSavedPhotosAlbum(myImage, self, nil, nil)
        })
    }
}

Comments