使用 CATextLayer 将文本绘制到 UIView 不工作

Draw text to UIView with CATextLayer not working

我正在尝试使用 CATextLayer 将文本绘制到 UIView,但到目前为止没有显示任何内容。我一定是遗漏了一些简单的东西。

private func drawText(string: String, at: CGPoint, withFont: CGFont, fontColor: CGColor, fontSize: CGFloat) -> CATextLayer {
    let textLayer = CATextLayer()
    textLayer.string = string
    textLayer.font = withFont
    textLayer.fontSize = fontSize
    textLayer.alignmentMode = .center
    textLayer.contentsScale = UIScreen.main.scale
    textLayer.position = at
    return textLayer
}

函数调用

let string = String(increment * Double(6 - i))
let textLayer = drawText(string: string, at: CGPoint(x: 30, y: CGFloat((i * 19) + 18)), withFont: someCGFont, fontColor: UIColor.black.cgColor, fontSize: 10)
    
chart.layer.addSublayer(textLayer)

您没有设置 CALayer 框架,请检查此测试源并根据您的要求进行自定义:

class ViewController: UIViewController {
    
    @IBOutlet weak var viewTest: UIView!
    
    private lazy var sampleLayer: CATextLayer = {
        let layer = CATextLayer()
        layer.fontSize = UIFont.systemFontSize
        layer.frame = self.viewTest.frame
        layer.string = "Test ABC"
        layer.foregroundColor = UIColor.blue.cgColor
        layer.contentsScale = UIScreen.main.scale
        layer.alignmentMode = CATextLayerAlignmentMode.left
        return layer
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.viewTest.layer.addSublayer(sampleLayer)
    }
}