这是我的第一个问题,所以如果我不清楚,请原谅。
我希望能够从现有UIImage1上的徒手绘制形状的内容创建一个新的UIImage2,以显示在现有UIImage1上。
一个视觉示例:UIImage1是城市天际线的照片。用户应该能够在摩天大楼周围绘制轮廓,并创建一个新的UIImage2,该UIImage2将堆叠显示在UIImage1上,并具有编辑UIImage 2的功能(大小,颜色等)。
在UIImage上绘制线条并不是太困难,但是我还没有弄清楚如何从徒手绘制的形状中创建单独的UIImage的方式从UIImage捕获内容。
非常感谢您的帮助。
答案 0 :(得分:1)
如果要从遮罩的路径创建图像,则可以:
UIBezierPath
CAShapeLayer
UIGraphicsBeginImageContextWithOptions
开始图像渲染过程; drawHierarchy
渲染应在图像中捕获的任何内容; UIGraphicsGetImageFromCurrentImageContext
从您渲染的图像中捕获图像,并且UIGraphicsEndImageContext
表示图像渲染过程已完成。例如:
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
private var path: UIBezierPath?
private var strokeLayer: CAShapeLayer?
@IBAction func didHandlePan(_ gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: imageView)
switch gesture.state {
case .began:
path = UIBezierPath()
path?.move(to: location)
strokeLayer = CAShapeLayer()
imageView.layer.addSublayer(strokeLayer!)
strokeLayer?.strokeColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1).cgColor
strokeLayer?.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
strokeLayer?.lineWidth = 5
strokeLayer?.path = path?.cgPath
case .changed:
path?.addLine(to: location)
strokeLayer?.path = path?.cgPath
case .cancelled, .ended:
// remove stroke from image view
strokeLayer?.removeFromSuperlayer()
strokeLayer = nil
// mask the image view
let mask = CAShapeLayer()
mask.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
mask.strokeColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
mask.lineWidth = 0
mask.path = path?.cgPath
imageView.layer.mask = mask
// get cropped image
guard let image = imageView?.snapshot else { return }
imageView.layer.mask = nil
// perhaps use that image?
imageView.image = image
default: break
}
}
}
顺便说一句,要从一个视图(蒙版或其他)创建UIImage
,您可以使用:
extension UIView {
var snapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
产生类似: