我是 Swift 和 Core Animation 的新手。我想像这张图片一样在 CAShapeLayer 周围创建矩形框,但我不知道。
详细地说,我正在通过PocketSVG解析 SVG 图像并将其UIBezierPath转换为CAShapeLayer,然后我将这些层添加到UI Image View作为sublayer。
这是我将Path转换为CaShape Layer的代码。
fileprivate func createLayer(path: SVGBezierPath) -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
if let any = path.svgAttributes["stroke"] {
shapeLayer.strokeColor = (any as! CGColor)
}
if let any = path.svgAttributes["fill"] {
shapeLayer.fillColor = (any as! CGColor)
}
return shapeLayer
}
下面是代码,我在其中将图层添加到 UIImage View (backgroundIV)
for path in paths {
path.apply(.init(scaleX: scale, y: scale))
let layer = createLayer(path: path)
layer.frame = self.backgroundIV.bounds
self.backgroundIV.layer.addSublayer(layer)
}
我还将TapGesture、RotateGesture、ScaleGesture 和 PanGesture 添加到 CA 形状图层,下面是代码。
@objc func rotateLayer(_ sender: UIRotationGestureRecognizer) {
selectedLayer?.setAffineTransform(CGAffineTransform(rotationAngle: sender.rotation))
}
@objc func selectLayer(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: self.backgroundIV)
guard let layers = self.backgroundIV.layer.sublayers
else { return }
var hitLayers: [CAShapeLayer] = []
selectedLayer?.lineWidth = CGFloat(0)
for subLayer in layers {
if let thisLayer = subLayer as? CAShapeLayer,
let pth = thisLayer.path {
let layerPoint: CGPoint = thisLayer.convert(point, from: self.backgroundIV.layer)
if pth.contains(layerPoint) {
hitLayers.append(thisLayer)
}
}
}
selectedLayer = hitLayers.last
selectedLayer?.strokeColor = UIColor.red.cgColor
selectedLayer?.lineWidth = CGFloat(3)
selectedLayerRect = CGRect(origin: point, size: CGSize(width: 100, height: 100))
showPopupMenu()
}
@objc func moveLayer(_ recognizer: UIPanGestureRecognizer) {
let p = recognizer.location(in: self.backgroundIV)
selectedLayer?.position = p
}
@objc func scaleLayer(_ sender: UIPinchGestureRecognizer) {
selectedLayer?.transform = CATransform3DMakeScale(sender.scale, sender.scale, 1)
}
在SelectLayer方法的最后几行中,我通过增加其笔触宽度和颜色来突出显示所选图层。
selectedLayer?.strokeColor = UIColor.red.cgColor
selectedLayer?.lineWidth = CGFloat(3)
当我选择图层时,我只是将它的lineWidth值设置为 0,这不是一个好习惯。
有没有办法像这张图片一样创建矩形框?