我正在解析 SVG 图像文件并将其路径转换为 CAShapeLayer,之后我将此 CAShapeLayer 添加到 UIImage View 的图层中。它工作正常,但问题是它不适合 UIImage 视图。那是输出。 图 1。这是向 UIImageView 添加图层的代码
if let svgURL = Bundle.main.url(forResource: "image", withExtension: "svg") {
let paths = SVGBezierPath.pathsFromSVG(at: svgURL)
for path in paths {
items.append(path)
let layer = createLayer(path: path)
layer.frame = self.backgroundIV.bounds
self.backgroundIV.layer.addSublayer(layer)
}
} // Create Layer from Paths Method
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
}
我搜索并添加了这两行代码,我得到了这个结果
let scale = CGFloat(0.5)
for path in paths {
path.apply(CGAffineTransform(scaleX: scale, y: scale))
items.append(path)
let layer = createLayer(path: path)
layer.frame = self.backgroundIV.bounds
self.backgroundIV.layer.addSublayer(layer)
}
那就是输出。 图 2
我不知道如何根据 uiImage View bounds计算scaleX
或scaleY
(在方法中使用)值CGAffineTransform
编辑 注意:我将触摸支持应用于 CAShapeLayer,这是代码。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
guard let point = touches.first?.location(in: self.backgroundIV),
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) {
// undoModel.append()
hitLayers.append(thisLayer)
}
}
}
selectedLayer = hitLayers.last
selectedLayer?.strokeColor = UIColor.red.cgColor
selectedLayer?.lineWidth = CGFloat(3)
undo.append(.init(stokeColor: nil, selectedLayer: selectedLayer, points: []))
if ((selectedLayer?.frame.contains(point)) != nil) {
isDragged = true
}
}