效果图
代码如下:
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
58
59
60
| import UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
let mySession: AVCaptureSession! = AVCaptureSession()
let devices = AVCaptureDevice.devices()
var myDevice: AVCaptureDevice!
var qrCodeFrameView:UIView!
var myVideoLayer : AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
for device in devices{
if(device.position == AVCaptureDevicePosition.Back){
myDevice = device as AVCaptureDevice
}
}
let myVideoInput = AVCaptureDeviceInput.deviceInputWithDevice(myDevice, error: nil) as AVCaptureDeviceInput
if mySession.canAddInput(myVideoInput) {
mySession.addInput(myVideoInput)
}
let myMetadataOutput: AVCaptureMetadataOutput! = AVCaptureMetadataOutput()
if mySession.canAddOutput(myMetadataOutput) {
mySession.addOutput(myMetadataOutput)
myMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
myMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
}
myVideoLayer = AVCaptureVideoPreviewLayer.layerWithSession(mySession) as AVCaptureVideoPreviewLayer
myVideoLayer.frame = self.view.bounds
myVideoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(myVideoLayer)
qrCodeFrameView = UIView()
qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor
qrCodeFrameView.layer.borderWidth = 2
self.view.addSubview(qrCodeFrameView)
self.view.bringSubviewToFront(qrCodeFrameView)
mySession.startRunning()
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if metadataObjects.count > 0 {
let qrData: AVMetadataMachineReadableCodeObject = metadataObjects[0] as AVMetadataMachineReadableCodeObject
let barCodeObject = myVideoLayer.transformedMetadataObjectForMetadataObject(qrData as AVMetadataMachineReadableCodeObject) as AVMetadataMachineReadableCodeObject
self.qrCodeFrameView.frame = barCodeObject.bounds
// UIApplication.sharedApplication().openURL(NSURL(string: qrData.stringValue)!)
} else {
self.qrCodeFrameView.frame = CGRectZero
}
}
}
|