Swift - Playground - Core Graphics / Core Text / Custom View

前端 未结 1 1042
陌清茗
陌清茗 2021-02-10 07:11

Question

I\'m attempting to make a custom UIView component in swift playground. I\'ve been able to figure out how to do everything except for render text correctly. I

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 07:57

    I wrote a utility function for my app to draw text using CoreText. It returns the text size for further processing:

    func drawText(context: CGContextRef, text: NSString, attributes: [String: AnyObject], x: CGFloat, y: CGFloat) -> CGSize {
        let font = attributes[NSFontAttributeName] as UIFont
        let attributedString = NSAttributedString(string: text, attributes: attributes)
    
        let textSize = text.sizeWithAttributes(attributes)
    
        // y: Add font.descender (its a negative value) to align the text at the baseline
        let textPath    = CGPathCreateWithRect(CGRect(x: x, y: y + font.descender, width: ceil(textSize.width), height: ceil(textSize.height)), nil)
        let frameSetter = CTFramesetterCreateWithAttributedString(attributedString)
        let frame       = CTFramesetterCreateFrame(frameSetter, CFRange(location: 0, length: attributedString.length), textPath, nil)
    
        CTFrameDraw(frame, context)
    
        return textSize
    }
    

    Call it like so:

    var textAttributes: [String: AnyObject] = [
        NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
        NSFontAttributeName : UIFont.systemFontOfSize(17)
    ]
    
    drawText(ctx, text: "Hello, World!", attributes: textAttributes, x: 50, y: 50)
    

    Hope that helps you.

    0 讨论(0)
提交回复
热议问题