如何通过拖动移动图层



如何在我将 CATextLayer 添加到 UIImageView Layer 后通过拖动来移动图层。因为我将向UIImageView添加多个层。那么,我如何知道我单击了哪个图层并将其移动到另一个位置?

这是我绘制文本的代码:

func addText() -> CATextLayer{
    let rect:CGRect = CGRect(x: 50, y: 600, width: 120, height: 60)
    let myAttributes = [
                        NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size:18)!,
                        NSForegroundColorAttributeName: UIColor.black.cgColor
                        ] as [String : Any]
    let myAttributedString = NSAttributedString(string: "TEST STRING", attributes: myAttributes)
    let textLayer = CATextLayer()
    textLayer.frame = rect
    textLayer.string = myAttributedString
    textLayer.position = CGPoint(x:150,y:400)
    textLayer.alignmentMode = kCAAlignmentCenter
    return textLayer
}

UIGestureRecognizerhitTest()是要走的路:

@IBOutlet weak var imageView: ImageView!
let panGesture = UIPanGestureRecognizer()
var newLayer = CATextLayer()
// this is your code above, be careful, you want each layer "named"!
nextLayer = addText()
imageView.layer.addSubLayer(nextLayer)
imageView.addGestureRecognizer(panGesture)
func moveLayer(_ recognizer:UIPanGestureRecognizer) {
    let p = recognizer.location(in: self)
    if newLayer.hitTest(p) != nil {
        newLayer.position = p
    }
}

仅此而已。我的代码是一个框架,我假设你想要图像视图中的层。但如果你愿意,它们可以成为超级视图的一部分。

同样,请注意设置图层的方式 - 如果要移动多个图层,则需要专门访问它们。我的代码是尝试使用您的函数。也许您可以将图层存储在数组中(如果您不知道会有多少层)或作为全局变量存储到 imageView 或视图控制器中。

最新更新