代码之家  ›  专栏  ›  技术社区  ›  Sweeper

如何在UILabel的文本下绘制内容?

  •  0
  • Sweeper  · 技术社区  · 6 年前

    我创造了一个习惯 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) 因为我以为那样会画出标签的文字,但当我运行应用程序时,我只看到圆圈,而看不到标签文字。

    超级绘图(矩形) 绘制标签的文本?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Sweeper    6 年前

    文本不可见,因为 UIBezierPath s取决于它们的绘制顺序。换句话说,, 尤比齐尔路径

    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 作为它的子视图。这种方法的优点是它不依赖于 super.draw(_:)