Search code examples
iphoneswiftcameramask

How to add circular mask on camera in swift


Now I am swift newbie but I want to learn how to add circular mask on Camera in swift. Now I am using Xcode7.2.1, swift 2.1, but I have no idea for that. And I am developing this camera application by using the https://github.com/imaginary-cloud/CameraManager as third party library. Here, I want to add my custom circular mask on Camera. I am wondering who can help me to get this! Thanks


Solution

  • UIImagePickerController has an cameraOverlayView property which you can use to provide a custom view that will act as an overlay. The example below creates an overlay view which is a square. Experiment with it to get what you want.

    @IBAction func takePhoto(sender: AnyObject) {
    
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            return
        }
    
        var imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
    
        //Create camera overlay
        let pickerFrame = CGRectMake(0, UIApplication.sharedApplication().statusBarFrame.size.height, imagePicker.view.bounds.width, imagePicker.view.bounds.height - imagePicker.navigationBar.bounds.size.height - imagePicker.toolbar.bounds.size.height)
        let squareFrame = CGRectMake(pickerFrame.width/2 - 200/2, pickerFrame.height/2 - 200/2, 200, 200)
        UIGraphicsBeginImageContext(pickerFrame.size)
    
        let context = UIGraphicsGetCurrentContext()
        CGContextSaveGState(context)
        CGContextAddRect(context, CGContextGetClipBoundingBox(context))
        CGContextMoveToPoint(context, squareFrame.origin.x, squareFrame.origin.y)
        CGContextAddLineToPoint(context, squareFrame.origin.x + squareFrame.width, squareFrame.origin.y)
        CGContextAddLineToPoint(context, squareFrame.origin.x + squareFrame.width, squareFrame.origin.y + squareFrame.size.height)
        CGContextAddLineToPoint(context, squareFrame.origin.x, squareFrame.origin.y + squareFrame.size.height)
        CGContextAddLineToPoint(context, squareFrame.origin.x, squareFrame.origin.y)
        CGContextEOClip(context)
        CGContextMoveToPoint(context, pickerFrame.origin.x, pickerFrame.origin.y)
        CGContextSetRGBFillColor(context, 0, 0, 0, 1)
        CGContextFillRect(context, pickerFrame)
        CGContextRestoreGState(context)
    
        let overlayImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
    
        let overlayView = UIImageView(frame: pickerFrame)
        overlayView.image = overlayImage
        imagePicker.cameraOverlayView = overlayView
        self.presentViewController(imagePicker, animated: true, completion: nil)
    
    }