是否在应用程序中的相机视图上方添加对象(Swift 3)而不是在相机视图下方添加对象? [英] Adding objects over camera view in app (Swift 3) not under camera view?

查看:82
本文介绍了是否在应用程序中的相机视图上方添加对象(Swift 3)而不是在相机视图下方添加对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在由红色圆圈组成的摄影机视图上有一个叠加层,存储在Assets.xcasset ImgOverlay占位符中,并且cameraview(预览)出现在该叠加层的后面或下面.没关系.应该的. 当我在iPhone上运行该应用程序时,覆盖图应会出现.参见图1 但是我还绘制了一个蓝色圆圈,即在相机视图"下方,并且仅在缺少相机视图时才会显示.即关闭或在模拟器上运行.参见下面的图2.

I have an overlay over the camera view made up of red circles, stored in the Assets.xcasset ImgOverlay placeholders, and the cameraview (preview) appears behind - or underneath - the overlay. That's fine. As it should be. When I run the app on the iPhone, the overlay appears as it should. See Img.1 But I also have a blue circle being drawn, that is Underneath the Camera View, and only appears if the camera view is missing. That is, Turned off, or run on a simulator. See Img.2 below.

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

图像2.红色圆圈,包括在模拟器中绘制的蓝色圆圈
到目前为止,我的代码在这里.我做错了,但看不到.我需要在iPhone中可见的蓝色圆圈,而不仅仅是在Simulator中.我试图绘制所有圆圈,所以可以放弃image.png类型文件中的红色圆圈.我更喜欢在所有设备上绘制圆圈以提高准确性,然后显示它们而不是红色圆圈,然后保存圆圈和相机视图的合成图像.保存时我还没有设法合并图像,但是第一步要在iPhone上显示蓝色圆圈... 因此,它几乎可以正常工作.我看不到我在做什么错?

Image 2. red circles including drawn blue circle in Simulator
The code I have so far is here. I'm doing something wrong, but can't see it. I need the blue circle(s) visible in the iPhone, not just in the Simulator. I'm trying to draw all the circles, so I can abandon the red circles which are in a image.png type file. I prefer to draw the circles for better accuracy across any device, and display them instead of the red circles, and then save the composite image, of the circles and the camera view. I haven't yet managed to combine the images when saved either, but getting the blue circle visible on the iPhone is the first step ... So it's almost fully working. I can't see what I'm doing wrong?

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.
}

}

推荐答案

您非常接近...

您有:

@IBOutlet weak var shapeLayer: UIView!

但随后您还创建了一个名为shapeLayer的CAShapeLayer:

but then you also create a CAShapeLayer named shapeLayer:

let shapeLayer = CAShapeLayer()

,您将其添加为主"视图的子层.然后,将 上的所有其他内容添加到主视图之上,覆盖shapeLayer.

which you add as a Sublayer of your "main" view. You then add everything else on top of your main view, covering the shapeLayer.

在viewDidLoad()中,将您的蓝色圆圈绘制部分更改为此:

In viewDidLoad(), change your blue-circle-drawing section to this:

    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()结束时...

Then, at the end of 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)

看看你会得到什么:)

后续问题移至将CameraView中的图像与覆盖. (快速3)?

这篇关于是否在应用程序中的相机视图上方添加对象(Swift 3)而不是在相机视图下方添加对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆