子视图中两个CGPoints之间的直线 - 无法确定嵌套子视图的框架

时间:2016-06-17 06:33:56

标签: ios swift uiview

我试图在两个CGPoints之间画一条线,我附上图片以供参考。 View Hierarchy

我无法确定嵌套在视图层次结构中的子视图的框架。我尝试过使用: -

let framev1 = self.view.convertRect(subview.frame, fromView: self.containerView)

如何获得深度嵌套在视图层次结构中的子视图的精确坐标?

使用此功能绘制两个CGPoint I之间的线:

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    let path = UIBezierPath()
    path.moveToPoint(start)
    path.addLineToPoint(end)

    //design path in layer
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath
    shapeLayer.strokeColor = lineColor.CGColor
    shapeLayer.lineWidth = 2.0

    view.layer.addSublayer(shapeLayer)
}

//我打算如何调用上面的函数为我画一条线。 显然这不起作用,它绘制了UIViewController.view的(0,0)行

func viewDidLoad() {
    super.viewDidLoad()

  drawLineFromPoint(CGPointMake(subview1.frame.minX,subview1.frame.midY),  toPoint:CGPointMake(subview2.frame.maxX,subview2.frame.midY ), ofColor: UIColor.redColor().colorWithAlphaComponent(1), inView: self.view)                  
}

1 个答案:

答案 0 :(得分:0)

对于第一个问题,请尝试使用此功能:

func convertRectCorrectly(rect: CGRect, toView view: UIView) -> CGRect {
    if UIScreen.mainScreen().scale == 1 {
        return self.convertRect(rect, toView: view)
    }
    else if self == view {
        return rect
    }
    else {
        var rectInParent = self.convertRect(rect, toView: self.superview)
        rectInParent.origin.x /= UIScreen.mainScreen().scale
        rectInParent.origin.y /= UIScreen.mainScreen().scale
        let superViewRect = self.superview!.convertRectCorrectly(self.superview!.frame, toView: view)
        rectInParent.origin.x += superViewRect.origin.x
        rectInParent.origin.y += superViewRect.origin.y
        return rectInParent
    }
}

示例:

let framev1 = self.view.convertRectCorrectly(subview.frame, toView: self.containerView)

它应该返回父容器视图中的子视图坐标。