我创建了一个自定义 UILabel
子类,它的中间有一个圆圈,标签的文本(数字)将位于圆圈的顶部。
我最初考虑使用layer.cornerRadius
来实现这一点,但是当标签的宽度和高度不相等时,这不会创建一个圆圈。
我的意思是,对于宽度为 100、高度为 50 的标签,我仍然想要一个半径为 50、中心位于 (50, 25) 的圆。
因此,我尝试使用UIBezierPath
来绘制圆。这是我尝试过的:
override func draw(_ rect: CGRect) {
super.draw(rect)
if bounds.height > bounds.width {
let y = (bounds.height - bounds.width) / 2
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: y, width: bounds.width, height: bounds.width))
circleColor.setFill()
path.fill()
} else {
let x = (bounds.width - bounds.height) / 2
let path = UIBezierPath(ovalIn: CGRect(x: x, y: 0, width: bounds.height, height: bounds.height))
circleColor.setFill()
path.fill()
}
}
我放置了 super.draw(rect)
因为我认为这会绘制标签的文本,但是当我运行应用程序时,我只看到圆圈而不是标签文本。
我很困惑,因为为什么 super.draw(rect)
没有绘制标签的文本?
最佳答案
看不到文本,因为 UIBezierPath 的“z-index”取决于它们的绘制顺序。换句话说,UIBezierPath
是在彼此之上绘制的。
super.draw(rect)
确实绘制了文本。但是,当您将其作为第一个语句时,它将首先绘制,因此您之后绘制的所有内容都位于文本之上。要解决此问题,您应该最后调用 super.draw(rect)
:
override func draw(_ rect: CGRect) {
if bounds.height > bounds.width {
let y = (bounds.height - bounds.width) / 2
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: y, width: bounds.width, height: bounds.width))
circleColor.setFill()
path.fill()
} else {
let x = (bounds.width - bounds.height) / 2
let path = UIBezierPath(ovalIn: CGRect(x: x, y: 0, width: bounds.height, height: bounds.height))
circleColor.setFill()
path.fill()
}
super.draw(rect) // <------- here!
}
或者,只需子类 UIView
,在 draw(_:)
中绘制圆圈,然后添加 UILabel
作为其 subview 。这种方法的优点是它不依赖于 super.draw(_:)
的实现,该实现将来可能会发生变化,
关于ios - 如何在 UILabel 的文本下绘制内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015404/