Drawing text over Core Graphics in Swift 3

前端 未结 2 1703
抹茶落季
抹茶落季 2021-02-12 22:51

Background: I am drawing on a UIImageView with Core Graphics. I would like to ultimately draw a text string over the core graphics drawing.

This (hackingwithswift.com) m

相关标签:
2条回答
  • 2021-02-12 23:14

    Swift 3.0 : to draw text

       func drawMyText(myText:String,textColor:UIColor, FontName:String, FontSize:CGFloat, inRect:CGRect){
    
         let textFont = UIFont(name: FontName, size: FontSize)!
        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]
    
        myText.draw(in: inRect, withAttributes: textFontAttributes)
    }
    

    call this function , below is e.g.

    let _rect = CGRect(x: 40, y: 100, width: 40, height: 40)
    
     drawMyText(myText: "Hello", textColor: UIColor.black, FontName: "Helvetica Bold", FontSize: 11 , inRect:_rect)
    
    0 讨论(0)
  • 2021-02-12 23:18

    Using Swift 4:

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    
    let attributes = [
        NSAttributedStringKey.paragraphStyle: paragraphStyle,
        NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12.0),
        NSAttributedStringKey.foregroundColor: UIColor.blue
    ]
    
    let myText = "HELLO"
    let attributedString = NSAttributedString(string: myText, attributes: attributes)
    
    let stringRect = CGRect(x: W/2 - 50, y: border, width: 100, height: H)
    attributedString.draw(in: stringRect)
    

    For Swift 4.2, change the above attributes to:

    let attributes: [NSAttributedString.Key : Any] = [
        .paragraphStyle: paragraphStyle,
        .font: UIFont.systemFont(ofSize: 12.0),
        .foregroundColor: UIColor.blue
    ]
    
    0 讨论(0)
提交回复
热议问题