绘制矩形以在滚动过程中不脱离屏幕

Draw rectangle to not fall off screen during scroll

我正在使用带有标记矩形的图表库,该标记矩形根据十字准线的位置显示数据。现在它以 y 轴线为中心,以 x 轴线为中心。但是如果 select 值太远 left/right/up/down,矩形将被切断并从屏幕上掉下来。如果它要在右侧被切断,我怎样才能让它移动到仍然在 y 轴线上方但在 x 轴线的左侧而不是在它的中心。同样,如果它会在左侧、顶部、底部被切断,但方向相反。

    override func draw(context: CGContext, point: CGPoint) {
        // custom padding around text
        let labelWidth = labelText.size(withAttributes: attrs).width + 20
        // if you modify labelHeigh you will have to tweak baselineOffset in attrs
        let labelHeight = labelText.size(withAttributes: attrs).height + 5 //Me


        // place pill above the marker, centered along x
        var rectangle = CGRect(x: point.x, y: point.y, width: labelWidth, height: labelHeight)// + 10) Me
        rectangle.origin.x -= rectangle.width / 2.0
        let spacing: CGFloat = 10
        rectangle.origin.y -= rectangle.height + spacing

        // rounded rect
        let clipPath = UIBezierPath(roundedRect: rectangle, cornerRadius: 6.0).cgPath
        context.addPath(clipPath)
        context.setFillColor(color.cgColor)
        context.setStrokeColor(color.darker(by: 10)!.cgColor)



//        context.setStrokeColor(color.)
        context.closePath()
        context.drawPath(using: .fillStroke)

        // add the text
        labelText.draw(with: rectangle, options: .usesLineFragmentOrigin, attributes: attrs, context: nil)  //usesLineFragmentOrigin
    }

通过此处看到的愚蠢的简单修复解决了问题。刚刚检查原点是否跨越了各自的值并相应地移动了它们,因为该代码随着十字准线在绘图上的每次移动而被调用。

var rectangle = CGRect(x: point.x, y: point.y, width: labelWidth, height: labelHeight)// + 10) Me
    rectangle.origin.x -= rectangle.width / 2.0

    if rectangle.origin.x + (rectangle.width) > UIScreen.main.bounds.width {
        rectangle.origin.x -= (rectangle.width / 2.0) + 10
    } else if rectangle.origin.x < 0 {
        rectangle.origin.x += (rectangle.width / 2.0) + 10
    }

    let spacing: CGFloat = 10
    rectangle.origin.y -= rectangle.height + spacing

    if rectangle.origin.y < spacing {
        rectangle.origin.y += 20 + (rectangle.height)
    }