在应用程序(Swift 3)中的摄像机视图上添加对象,而不是在摄像机视图下?

时间:2017-03-03 12:59:59

标签: ios swift3 camera-overlay

我在由红色圆圈组成的摄像机视图上有一个叠加层,存储在Assets.xcasset ImgOverlay占位符中,并且摄像机视图(预览)出现在叠加层的后面或下面。没关系。应该如此。 当我在iPhone上运行应用程序时,叠加层会出现。见Img.1  但我也画了一个蓝色圆圈,即在摄影机视图下方,只有在相机视图丢失时才会出现。也就是说,关闭,或在模拟器上运行。见下面的Img.2。

图片1.红色圆圈在相机视图上,在iPhone中

Image 1. red circles over camera view, in iPhone

图像2.红色圆圈,包括模拟器中绘制的蓝色圆圈 Image 2. red circles including drawn blue circle in Simulator
我到目前为止的代码就在这里。我做错了什么,却看不到。我需要iPhone中可见的蓝色圆圈,而不仅仅是在模拟器中。我正在尝试绘制所有圆圈,因此我可以放弃image.png类型文件中的红色圆圈。我更喜欢在任何设备上绘制圆圈以获得更好的精确度,并显示它们而不是红色圆圈,然后保存合成图像,圆圈和相机视图。我还没有设法在保存时合并图像,但是在iPhone上看到蓝色圆圈是第一步...... 所以它几乎完全正常工作。我看不出我做错了什么?

ViewController.swift

import UIKit
import AVFoundation
import Foundation

class ViewController: UIViewController {

@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var imgOverlay: UIImageView!
@IBOutlet weak var btnCapture: UIButton!

@IBOutlet weak var shapeLayer: UIView!

let captureSession = AVCaptureSession()
let stillImageOutput = AVCaptureStillImageOutput()
var previewLayer : AVCaptureVideoPreviewLayer?

//var shapeLayer : CALayer?

// 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.
    //=======================

    let midX = self.view.bounds.midX
    let midY = self.view.bounds.midY

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: midX,y: midY), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()

    shapeLayer.path = circlePath.cgPath
    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.blue.cgColor
    //you can change the line width
    shapeLayer.lineWidth = 2.5

    view.layer.addSublayer(shapeLayer)
    print("Shape layer drawn")
    //=====================
    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] {
        // 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
                    if captureDevice != nil {
                        print("Capture device found")
                        beginSession()
                    }
                }
            }
        }
    }
}

@IBAction func actionCameraCapture(_ sender: AnyObject) {

    print("Camera button pressed")
    saveToCamera()
}

func beginSession() {

    do {
        try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
        stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput) {
            captureSession.addOutput(stillImageOutput)
        }

    }
    catch {
        print("error: \(error.localizedDescription)")
    }

    guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else {
        print("no preview layer")
        return
    }
    // this is what displays the camera view. But - it's on TOP of the drawn view, and under the overview. ??
    self.view.layer.addSublayer(previewLayer)
    previewLayer.frame = self.view.layer.frame



    captureSession.startRunning()
    print("Capture session running")


    self.view.addSubview(navigationBar)
    self.view.addSubview(imgOverlay)
    self.view.addSubview(btnCapture)
        }

func saveToCamera() {

    if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
          stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, Error) in

            if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer) {
                if let cameraImage = UIImage(data: imageData) {


                   UIImageWriteToSavedPhotosAlbum(cameraImage, nil, nil, nil)

                }
            }
        })
    }
}



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

}

1 个答案:

答案 0 :(得分:1)

你非常接近......

你有:

@IBOutlet weak var shapeLayer: UIView!

但是你也创建了一个名为shapeLayer的CAShapeLayer:

let shapeLayer = CAShapeLayer()

您添加为“主要”视图的子图层。然后,在主视图的 上添加 的所有内容,覆盖shapeLayer。

在viewDidLoad()中,将蓝色圆圈绘图部分更改为:

    let midX = self.view.bounds.midX
    let midY = self.view.bounds.midY

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: midX,y: midY), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    let shapeLayerPath = CAShapeLayer()

    shapeLayerPath.path = circlePath.cgPath
    //change the fill color
    shapeLayerPath.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayerPath.strokeColor = UIColor.blue.cgColor
    //you can change the line width
    shapeLayerPath.lineWidth = 2.5

    // add the blue-circle layer to the shapeLayer ImageView
    shapeLayer.layer.addSublayer(shapeLayerPath)

    print("Shape layer drawn")
    //=====================

然后,在beginSession()的末尾......

    self.view.addSubview(navigationBar)
    self.view.addSubview(imgOverlay)
    self.view.addSubview(btnCapture)

    // shapeLayer ImageView is already a subview created in IB
    // but this will bring it to the front
    self.view.addSubview(shapeLayer)

    // note: since these elements are added as @IBOutlet in IB,
    // these could be:

    // self.view.bringSubview(toFront: navigationBar)
    // self.view.bringSubview(toFront: imgOverlay)
    // self.view.bringSubview(toFront: btnCapture)
    // self.view.bringSubview(toFront: shapeLayer)

看看你得到了什么:)

修改:后续问题已移至Combining Images in CameraView with Overlay. (Swift 3)?