如何通过拖动来移动图层? [英] how to move a layer by dragging?
问题描述
在将CATextLayer添加到UIImageView图层后,如何通过拖动来移动图层。因为我将在UIImageView中添加多个层。因此,我怎么知道我单击了哪一层并将其移动到另一个位置?
How to move a layer by dragging after I added the CATextLayer to UIImageView Layer. As I will add more than one layer to UIImageView. So, How can I know which layer I clicked and move it to another position?
这是我绘制文本的代码:
Here is my code for drawing text:
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
}
推荐答案
UIGestureRecognizer
和 hitTest()
是解决方法:
@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内放置图层。
That's about it. My code is a skeleton where I'm assuming you want the layers inside the imageView. But they can be part of the superview if you want.
同样,请谨慎设置图层-如果您有多个图层,则需要专门访问它们到处走动。我的代码是尝试使用您的函数。也许您可以将图层存储在数组中(如果您不知道要存储多少),也可以将其存储为imageView或view controller的全局变量。
Again, be careful with how you set up the layers - you need to access them specifically if you have multiple ones to move around. My code was an attempt to use your function. Maybe you could store the layers in an array (if you don't know how many there will be) or as global variables to either the imageView or the view controller.
这篇关于如何通过拖动来移动图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!