Drawing Text with Core Graphics

后端 未结 3 1227
庸人自扰
庸人自扰 2021-02-02 02:15

I need to draw centered text to a CGContext.

I started with a Cocoa approach. I created a NSCell with the text and tried to draw it thus:

NSGraphicsConte         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 03:03

    Swift 5 version!

    let targetSize: CGSize = // the space you have available for drawing the text
    let origin: CGPoint = // where you want to position the top-left corner
    let string: String = // your string
    let font: UIFont = // your font
    
    let attrs: [NSAttributedString.Key:Any] = [.font: font]
    let boundingRect = string.boundingRect(with: targetSize, options: [.usesLineFragmentOrigin], attributes: attrs, context: nil)
    let textRect = CGRect(origin: origin, size: boundingRect.size)
    text.draw(with: textRect, options: [.usesLineFragmentOrigin], attributes: attrs, context: nil)
    

提交回复
热议问题