I have a svg image, when i touch the image i get the shapeLayer selected and I change its color but when i transform the image to move it in the device i need to touch the original position to detect the shapeLayer. I'm using PocketSVG.
This is my code:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
view.addGestureRecognizer(tapGesture)
view.isUserInteractionEnabled = true
svgView = SVGImageView.init(contentsOf: svgURl)
paths = SVGBezierPath.pathsFromSVG(at: svgURl)
for (index, path) in paths.enumerated() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = colors[index].cgColor
gamerCat.addSublayer(shapeLayer)}
var transform = CATransform3DMakeScale(0.4, 0.4, 1.0)
transform = CATransform3DTranslate(transform, 200, 400, 0)
gamerCat.transform = transform
gamerCat.shouldRasterize = false
svgView.layer.addSublayer(gamerCat)
view.addSubview(svgView)
@objc func handleTap(_ gesture: UITapGestureRecognizer) {
print("-----------------------------------")
let location = gesture.location(in: view)
print("Location : \(location)")
rects.removeAll(keepingCapacity: false)
indiceRect.removeAll(keepingCapacity: false)
elementTouched(location: location)
}
func elementTouched(location:CGPoint) {
let shapeLayer = CAShapeLayer()
for (index, path) in paths.enumerated() {
shapeLayer.path = path.cgPath
isRectContained(rectA: shapeLayer.path!.boundingBox, rectB: CGRect(x: location.x, y: location.y, width: 1, height: 1), index: index)
}
var smallestRect = rects.first
for rect in rects.dropFirst() {
if let currentSmallest = smallestRect {
if rect.width * rect.height < currentSmallest.width * currentSmallest.height {
smallestRect = rect
}
} else {
smallestRect = rect
}
}
if let smallestRect = smallestRect {
print("El CGRect más pequeño es: \(smallestRect)")
var elegido = indiceRect[rects.firstIndex(of: smallestRect)!]
shapeLayer.path = paths[elegido].cgPath
shapeLayer.fillColor = UIColor.red.cgColor
} else {
print("Array is empty.")
}
gamerCat.addSublayer(shapeLayer)
}
This is what I do, I don't know if I need to make a transform to move the image. I tried to move with svgView.frame but the size of the image don't change and i tried to use clips.blouns but my image disappear