问题描述
我正在将图表库与标记矩形一起使用,该标记矩形根据十字线所在的位置显示数据。现在,它以y轴线为中心,以x轴线为中心。但是,如果您选择的值太左/右/上/下太远,则矩形将被切除并从屏幕上掉落。如果要在右侧截断该怎么办,它将移动到仍在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)
}