我可以使用闪光灯功能、访问照片库以及使用后置/前置摄像头。
我想实现在用户拍照时显示的网格线。
有任何想法吗?
创建一个UIImageView
用于cameraOverlayView
.
假设您有一个UIImagePickerController
命名yourImagePickerController
并且您有一个名为overlay.png
“网格线”的图像文件。制作网格线图像文件时,请务必使用透明背景 - 而不是不透明的白色。
UIImageView *overlayImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"overlay.png"]];
CGRect overlayRect = CGRectMake(0, 0, overlayImage.image.size.width, overlayImage.image.size.height);
[overlayImage setFrame:overlayRect];
[yourImagePickerController setCameraOverlayView:overlayImage];
就文档而言,它没有说明 Apple 提供的网格线是否实际上是一种共享方法,但由于没有提及,我不会说,但您可以使用 cameraOverlayView 实现自己的。
这很容易UIBezierPath
。这就是你可以实现的方式。
将此代码保存在名为GridView.swift
.
import Foundation
import UIKit
class GridView: UIView {
override func draw(_ rect: CGRect) {
let firstColumnPath = UIBezierPath()
firstColumnPath.move(to: CGPoint(x: bounds.width / 3, y: 0))
firstColumnPath.addLine(to: CGPoint(x: bounds.width / 3, y: bounds.height))
let firstColumnLayer = gridLayer()
firstColumnLayer.path = firstColumnPath.cgPath
layer.addSublayer(firstColumnLayer)
let secondColumnPath = UIBezierPath()
secondColumnPath.move(to: CGPoint(x: (2 * bounds.width) / 3, y: 0))
secondColumnPath.addLine(to: CGPoint(x: (2 * bounds.width) / 3, y: bounds.height))
let secondColumnLayer = gridLayer()
secondColumnLayer.path = secondColumnPath.cgPath
layer.addSublayer(secondColumnLayer)
let firstRowPath = UIBezierPath()
firstRowPath.move(to: CGPoint(x: 0, y: bounds.height / 3))
firstRowPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 3))
let firstRowLayer = gridLayer()
firstRowLayer.path = firstRowPath.cgPath
layer.addSublayer(firstRowLayer)
let secondRowPath = UIBezierPath()
secondRowPath.move(to: CGPoint(x: 0, y: ( 2 * bounds.height) / 3))
secondRowPath.addLine(to: CGPoint(x: bounds.width, y: ( 2 * bounds.height) / 3))
let secondRowLayer = gridLayer()
secondRowLayer.path = secondRowPath.cgPath
layer.addSublayer(secondRowLayer)
}
private func gridLayer() -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor(white: 1.0, alpha: 0.3).cgColor
shapeLayer.frame = bounds
shapeLayer.fillColor = nil
return shapeLayer
}
}
用法:
func addGridView(cameraView: UIView) {
let horizontalMargin = cameraView.bounds.size.width / 4
let verticalMargin = cameraView.bounds.size.height / 4
let gridView = GridView()
gridView.translatesAutoresizingMaskIntoConstraints = false
cameraView.addSubview(gridView)
gridView.backgroundColor = UIColor.clear
gridView.leftAnchor.constraint(equalTo: cameraView.leftAnchor, constant: horizontalMargin).isActive = true
gridView.rightAnchor.constraint(equalTo: cameraView.rightAnchor, constant: -1 * horizontalMargin).isActive = true
gridView.topAnchor.constraint(equalTo: cameraView.topAnchor, constant: verticalMargin).isActive = true
gridView.bottomAnchor.constraint(equalTo: cameraView.bottomAnchor, constant: -1 * verticalMargin).isActive = true
}