我正在尝试向UIImageView添加4个UIView子视图。这些子视图将充当节点,用户可以在其中点击它们并连接到其他节点。例如,它们应该看起来像like this。相反,他们正在寻找like this。
我计算节点位置的代码如下:
func initializeConnectionNodes() {
let imageCenter = self.imageView.center
let xOffset = self.imageView.bounds.width/2 //distance from origin x-wise
let yOffset = self.imageView.bounds.height/2 //distance from origin y-wise
self.leftConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x - xOffset, y: imageCenter.y))
self.rightConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x + xOffset, y: imageCenter.y))
self.topConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x, y: imageCenter.y + yOffset))
self.bottomConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageCenter.x, y: imageCenter.y - yOffset))
self.imageView.addSubview(self.leftConnectionNode!)
self.imageView.addSubview(self.rightConnectionNode!)
self.imageView.addSubview(self.topConnectionNode!)
self.imageView.addSubview(self.bottomConnectionNode!)
}
我初始化UIView类的代码如下:
class ConnectionNodeView: UIView {
var connectionPoint: CGPoint
fileprivate var circleLayer: CAShapeLayer?
init(connectionPoint: CGPoint) {
self.connectionPoint = connectionPoint
super.init(frame: CGRect(x: connectionPoint.x, y: connectionPoint.y, width: 0, height: 0))
let circlePath = UIBezierPath(arcCenter: connectionPoint, radius: CGFloat(8), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
self.circleLayer = CAShapeLayer()
self.circleLayer?.path = circlePath.cgPath
self.circleLayer?.fillColor = UIColor.yellow.cgColor
self.circleLayer?.strokeColor = UIColor.yellow.cgColor
self.circleLayer?.lineWidth = 3.0
self.layer.addSublayer(circleLayer!)
}
有趣的是,如果我只是将CAShapeLayer作为子层添加到我的UIImageView中,它看起来应该是这样的。但是,我需要将它实现为UIView,这样我就可以轻松地使用手势识别器。我找到了一种糟糕的方法来修复它,在初始化器中将坐标除以100,如下所示:
super.init(frame: CGRect(x: connectionPoint.x/100, y: connectionPoint.y/100, width: 0, height: 0))
然而,我更愿意做正确的事情。这里我漏掉了什么?谢谢你的帮助。
发布于 2018-06-03 09:22:02
您正在将视图添加到图像视图,但是imageCenter
点是根据图像视图的superview指定的。
将initializeConnectionNodes
函数的开头替换为以下内容:
let xCenter = imageView.bounds.width / 2
let yCenter = imageView.bounds.height / 2
leftConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: 0, y: yCenter))
rightConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: imageView.bounds.width, y: yCenter))
topConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: xCenter, y: 0))
bottomConnectionNode = ConnectionNodeView(connectionPoint: CGPoint(x: xCenter, y: imageView.bounds.height))
另外,您应该将ConnectionNodeView
子类中circlePath
的弧形中心替换为CGPoint.zero
,因为它使用节点视图本身的坐标系:
let circlePath = UIBezierPath(arcCenter: .zero, radius: 8, startAngle: 0, endAngle:CGFloat(Double.pi * 2), clockwise: true)
https://stackoverflow.com/questions/50662231
复制相似问题