Advertisement
Guest User

Untitled

a guest
Nov 25th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. import AVFoundation
  2.  
  3. class ViewController: UIViewController, CLLocationManagerDelegate {
  4.  
  5. @IBOutlet weak var takePhotoButton: UIButton!
  6.  
  7. let captureSession = AVCaptureSession()
  8. var previewLayer: AVCaptureVideoPreviewLayer ?
  9.  
  10. // If we find a device we'll store it here for later use
  11. var captureDevice: AVCaptureDevice ?
  12.  
  13. func focusTo(value: Float) {
  14. if let device = captureDevice {
  15. if (device.lockForConfiguration(nil)) {
  16. device.setFocusModeLockedWithLensPosition(value, completionHandler: {
  17. (time) - > Void in
  18. })
  19. device.unlockForConfiguration()
  20. }
  21. }
  22. }
  23.  
  24. @IBAction func takePhotoButtonPressed(sender: UIButton) {
  25. captureSession.sessionPreset = AVCaptureSessionPresetHigh
  26.  
  27. let devices = AVCaptureDevice.devices()
  28.  
  29. // Loop through all the capture devices on this phone
  30. for device in devices {
  31. // Make sure this particular device supports video
  32. if (device.hasMediaType(AVMediaTypeVideo)) {
  33. // Finally check the position and confirm we've got the back camera
  34. if (device.position == AVCaptureDevicePosition.Back) {
  35. captureDevice = device as ? AVCaptureDevice
  36. if captureDevice != nil {
  37. println("Capture device found")
  38. beginSession()
  39. }
  40. }
  41. }
  42. }
  43. }
  44.  
  45. let screenWidth = UIScreen.mainScreen().bounds.size.width
  46. override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
  47. var anyTouch = touches.anyObject() as UITouch
  48. var touchPercent = anyTouch.locationInView(self.view).x / screenWidth
  49. focusTo(Float(touchPercent))
  50. }
  51.  
  52. override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
  53. var anyTouch = touches.anyObject() as UITouch
  54. var touchPercent = anyTouch.locationInView(self.view).x / screenWidth
  55. focusTo(Float(touchPercent))
  56. }
  57.  
  58. func configureDevice() {
  59. if let device = captureDevice {
  60. device.lockForConfiguration(nil)
  61. device.focusMode = .Locked
  62. device.unlockForConfiguration()
  63. }
  64.  
  65. }
  66.  
  67. func beginSession() {
  68.  
  69. configureDevice()
  70.  
  71. var err: NSError ? = nil
  72. captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: & err))
  73.  
  74. if err != nil {
  75. println("error: (err?.localizedDescription)")
  76. }
  77.  
  78. previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
  79. self.view.layer.addSublayer(previewLayer)
  80. previewLayer ? .frame = self.view.layer.frame
  81. captureSession.startRunning()
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement