在我的应用中,用户需要使用相机拍照,然后用手指在图像中标记一些区域。
所以我创建了UIImageView
来保存来自相机的图像,然后添加了UIPanGestureRecognizer来监听“绘图”手势:
panGesture = UIPanGestureRecognizer(target: self, action: #selector(AttachmentInputViewController.handlePanGesture(_:)))
imageView.addGestureRecognizer(panGesture!)
handlePanGesture:
func handlePanGesture(_ sender: UIPanGestureRecognizer) {
let point = sender.location(in: sender.view)
switch sender.state {
case .began:
self.startAtPoint(point: point)
case .changed:
self.continueAtPoint(point: point)
case .ended:
self.endAtPoint(point: point)
case .failed:
self.endAtPoint(point: point)
default:
assert(false, "State not handled")
}
}
然后我创建UIBezierPath
,其中包含“绘图”并使用这些标记创建单独的图像:
private func startAtPoint(point: CGPoint) {
path = UIBezierPath()
path.lineWidth = 5
path.move(to: point)
}
private func continueAtPoint(point: CGPoint) {
path.addLine(to: point)
}
private func endAtPoint(point: CGPoint) {
path.addLine(to: point)
path.addLine(to: point)
//path.close()
let imageWidth: CGFloat = imageView.image!.size.width
let imageHeight: CGFloat = imageView.image!.size.height
let strokeColor:UIColor = UIColor.red
// Make a graphics context
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
let context = UIGraphicsGetCurrentContext()
context!.setStrokeColor(strokeColor.cgColor)
//for path in paths {
path.stroke()
//}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
最后,我需要使用用户的标记保存图像。
问题是UIImageView
中的图像设置为scaleToFit
,当我尝试将相机图像和标记图像组合时,由于分辨率和比率不同,它们不匹配。
我觉得有更好的方法可以达到这个目标,如果有人能推荐一种最好的方式,我会很感激。