2015-12-30 15 views
8

ciao Vorrei aprire una macchina fotografica nella mia app come questoIOS Swift - overlay fotocamera personalizzato

enter image description here

voglio aprire una telecamera solo a metà della sezione così l'utente può prendere un gioco da ragazzi solo nella sezione rettangolare

il codice che sto usando questo

import UIKit 
import AVFoundation 

class TakeProductPhotoController: UIViewController { 

    let captureSession = AVCaptureSession() 
    var previewLayer : AVCaptureVideoPreviewLayer? 

    // If we find a device we'll store it here for later use 
    var captureDevice : AVCaptureDevice? 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view, typically from a nib. 
     captureSession.sessionPreset = AVCaptureSessionPresetHigh 

     let devices = AVCaptureDevice.devices() 

     // Loop through all the capture devices on this phone 
     for device in devices { 
      // Make sure this particular device supports video 
      if (device.hasMediaType(AVMediaTypeVideo)) { 
       // Finally check the position and confirm we've got the back camera 
       if(device.position == AVCaptureDevicePosition.Back) { 
        captureDevice = device as? AVCaptureDevice 
        if captureDevice != nil { 
         print("Capture device found") 
         beginSession() 
        } 
       } 
      } 
     } 

    } 
    func updateDeviceSettings(focusValue : Float, isoValue : Float) { 
     let error: NSErrorPointer = nil 

     if let device = captureDevice { 
      do { 
       try captureDevice!.lockForConfiguration() 

      } catch let error1 as NSError { 
       error.memory = error1 
      } 

       device.setFocusModeLockedWithLensPosition(focusValue, completionHandler: { (time) -> Void in 
        // 
       }) 

       // Adjust the iso to clamp between minIso and maxIso based on the active format 
       let minISO = device.activeFormat.minISO 
       let maxISO = device.activeFormat.maxISO 
       let clampedISO = isoValue * (maxISO - minISO) + minISO 

       device.setExposureModeCustomWithDuration(AVCaptureExposureDurationCurrent, ISO: clampedISO, completionHandler: { (time) -> Void in 
        // 
       }) 

       device.unlockForConfiguration() 

     } 
    } 

    func touchPercent(touch : UITouch) -> CGPoint { 
     // Get the dimensions of the screen in points 
     let screenSize = UIScreen.mainScreen().bounds.size 

     // Create an empty CGPoint object set to 0, 0 
     var touchPer = CGPointZero 

     // Set the x and y values to be the value of the tapped position, divided by the width/height of the screen 
     touchPer.x = touch.locationInView(self.view).x/screenSize.width 
     touchPer.y = touch.locationInView(self.view).y/screenSize.height 

     // Return the populated CGPoint 
     return touchPer 
    } 

    func focusTo(value : Float) { 
     let error: NSErrorPointer = nil 


     if let device = captureDevice { 
      do { 
       try captureDevice!.lockForConfiguration() 

      } catch let error1 as NSError { 
       error.memory = error1 
      } 

       device.setFocusModeLockedWithLensPosition(value, completionHandler: { (time) -> Void in 
        // 
       }) 
       device.unlockForConfiguration() 

     } 
    } 

    let screenWidth = UIScreen.mainScreen().bounds.size.width 

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     //if let touchPer = touches.first { 
      let touchPer = touchPercent(touches.first! as UITouch) 
     updateDeviceSettings(Float(touchPer.x), isoValue: Float(touchPer.y)) 


     super.touchesBegan(touches, withEvent:event) 
    } 

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     // if let anyTouch = touches.first { 
      let touchPer = touchPercent(touches.first! as UITouch) 
     // let touchPercent = anyTouch.locationInView(self.view).x/screenWidth 
    //  focusTo(Float(touchPercent)) 
    updateDeviceSettings(Float(touchPer.x), isoValue: Float(touchPer.y)) 

    } 

    func configureDevice() { 
      let error: NSErrorPointer = nil 
     if let device = captureDevice { 
      //device.lockForConfiguration(nil) 

      do { 
       try captureDevice!.lockForConfiguration() 

      } catch let error1 as NSError { 
       error.memory = error1 
      } 

      device.focusMode = .Locked 
      device.unlockForConfiguration() 
     } 

    } 

    func beginSession() { 
     configureDevice() 
     var err : NSError? = nil 

     var deviceInput: AVCaptureDeviceInput! 
     do { 
      deviceInput = try AVCaptureDeviceInput(device: captureDevice) 

     } catch let error as NSError { 
      err = error 
      deviceInput = nil 
     }; 


     captureSession.addInput(deviceInput) 

     if err != nil { 
      print("error: \(err?.localizedDescription)") 
     } 

     previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 

     self.view.layer.addSublayer(previewLayer!) 
     previewLayer?.frame = self.view.layer.frame 
     captureSession.startRunning() 
    } 
} 

in questo codice la fotocamera sta prendendo l'intero schermo.

+0

Puoi pubblicare il tuo progetto di story board mi sono bloccato nello stesso problema. –

+0

@NomanAkhtar sei ancora bloccato lì? – hellosheikh

+0

@hellosheikh Quindi, quali sono i fotogrammi aggiornati finali per previewLayer? e posso sapere come possiamo ottenere oggetti immagine dopo averli toccati? –

risposta

9

Se si desidera avviare la fotocamera in una personalizzata UIView, è necessario modificare AVCaptureVideoPreviewLayer. puoi cambiare i suoi limiti, la sua posizione, anche tu puoi aggiungere una maschera ad esso.

Venendo alla tua domanda, lo strato di acquisizione sta prendendo schermo intero perché si ha:

previewLayer?.frame = self.view.layer.frame 

Modificare questa linea per quel lasso di sovrapposizione

previewLayer?.frame = self.overLayView.layer.frame 

o, se si vuole posizionare la fotocamera livello manualmente utilizzando i valori non elaborati:

previewLayer?.frame = CGRectMake(x,y,width,height) 

Inoltre, si noti che, se si desidera iniziare la fotocamera in vista di sovrapposizione, è necessario aggiungere la visualizzazione secondaria a quella vista sovrapposizione

quindi questa linea:

 self.view.layer.addSublayer(previewLayer!) 

sarà questo:

self.overLayView.layer.addSublayer(previewLayer!) 

per allungare lo strato/adattare il preview layer:

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 

     var bounds:CGRect 
     bounds=cameraView.layer.frame; 
     previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill; 
     previewLayer!.bounds=bounds; 
     previewLayer!.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)); 

     self.view.layer.addSublayer(previewLayer!) 
+0

potresti dirmi come posso farlo .. Sono nuovo in IOS ... @ Mr.T – hellosheikh

+0

ho aggiornato la risposta –

+0

ho provato la mia risposta @hellosheikh –

Problemi correlati