我试图在两个CGPoint之间画一条线,并附上图片以供参考。 ios -  subview 中两个CGPoint之间的线-无法确定嵌套 subview 的框架-LMLPHP

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

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


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

为了在两个CGPoint之间绘制线,我使用了以下功能:

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)
}

最佳答案

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

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)


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

10-06 07:54