自定义相机视图 Swift iOS 8 iPhone Xcode 6.1

7
我想在我的iPhone上使用摄像头来拍照。我不想使用典型的全屏幕相机视图,而是自己的视图。
例如,我想在屏幕中央有一个200x200的正方形,在其内预览摄像头。在这个正方形下面,我想要一个按钮来拍照。如何实现?我是Swift初学者。

研究使用 cameraOverlayView - Lyndsey Scott
3个回答

10
您需要使用AVFoundation框架来创建自己的AVCaptureSession,并将其放置在您在Storyboard中创建的视图中。以下是一个很好的教程,向您展示如何查找摄像头并创建捕获会话:

http://jamesonquave.com/blog/taking-control-of-the-iphone-camera-in-ios-8-with-swift-part-1/

此教程将整个视图用作捕获视图,因此如果您按照他的代码进行建模,相机的大小将是这样。要在屏幕中央绘制一个200x200的正方形,您必须在Storyboard中的视图控制器上绘制一个正方形,将其链接到Swift文件中的变量,并更改底部的部分,该部分说:

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

希望这可以帮到你。如果不能,我可以尝试提供更多帮助,或者其他人可以纠正我。

祝你好运!

对于your200by200View.layer.frame,希望这样能够解决问题。


5
另一个代码块。如何在 iPhone 上进行手动对焦。
import UIKit

class ViewController: UIViewController {

    @IBOutlet var cameraView: CameraView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func sliderChanged(sender: UISlider) {
        cameraView.setFocusWithLensPosition(sender.value)
    }
}


import UIKit
import AVFoundation

class CameraView: UIView {

    // AVFoundation properties
    let captureSession = AVCaptureSession()
    var captureDevice: AVCaptureDevice!
    var captureDeviceFormat: AVCaptureDeviceFormat?
    let stillImageOutput = AVCaptureStillImageOutput()
    var cameraLayer: AVCaptureVideoPreviewLayer?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initCamera()
    }

    func initCamera() {
        captureSession.beginConfiguration()


        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

        // get the back camera
        if let device = cameraDeviceForPosition(AVCaptureDevicePosition.Back) {

            captureDevice = device
            captureDeviceFormat = device.activeFormat

            let error: NSErrorPointer = nil

            do {
                try captureDevice!.lockForConfiguration()
            } catch let error1 as NSError {
                error.memory = error1
            }
            captureDevice!.focusMode = AVCaptureFocusMode.Locked
            captureDevice!.unlockForConfiguration()

            var deviceInput: AVCaptureDeviceInput!
            do {
                deviceInput = try AVCaptureDeviceInput(device: captureDevice)
            } catch let error1 as NSError {
                error.memory = error1
                deviceInput = nil
            }
            if(error == nil) {
                captureSession.addInput(deviceInput)
            }

            captureSession.addOutput(stillImageOutput)

            // use the high resolution photo preset
            captureSession.sessionPreset = AVCaptureSessionPresetPhoto


            // setup camera preview
            cameraLayer = AVCaptureVideoPreviewLayer(session: captureSession)


            if let player = cameraLayer {
                player.videoGravity = AVLayerVideoGravityResizeAspectFill
                self.layer.addSublayer(player)
                player.frame = self.layer.bounds
                player.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
            }

            // commit and start capturing
            captureSession.commitConfiguration()
            captureSession.startRunning()
        }

        captureSession.commitConfiguration()
    }

    func setFocusWithLensPosition(pos: CFloat) {
        let error: NSErrorPointer = nil
        do {
            try captureDevice!.lockForConfiguration()
        } catch let error1 as NSError {
            error.memory = error1
        }
        captureDevice!.setFocusModeLockedWithLensPosition(pos, completionHandler: nil)
        captureDevice!.unlockForConfiguration()
    }

    // return the camera device for a position
    func cameraDeviceForPosition(position:AVCaptureDevicePosition) -> AVCaptureDevice?
    {
        for device:AnyObject in AVCaptureDevice.devices() {
            if (device.position == position) {
                return device as? AVCaptureDevice;
            }
        }

        return nil
    }

}

3

以下是如何添加 cameraOverlayView ,创建一个位于屏幕中心的200x200正方形查看窗口的示例:

@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)

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接