Drawing rotated text with NSString drawInRect

前端 未结 5 1843
借酒劲吻你
借酒劲吻你 2020-11-29 04:09

I found this answer on how to draw rotated text with NSString drawInRect:, but I\'m not sure how it works since it only sort of works for me: https://discussions.apple.com/t

5条回答
  •  情深已故
    2020-11-29 04:38

    Here'a an updated and simplified version of KoNEW's answer. It preserves the state of the graphics context as a bonus. This is also a simple function instead of a String extension.

    func drawRotatedText(_ text: String, at p: CGPoint, angle: CGFloat, font: UIFont, color: UIColor) {
      // Draw text centered on the point, rotated by an angle in degrees moving clockwise.
      let attrs = [NSFontAttributeName: font, NSForegroundColorAttributeName: color]
      let textSize = text.size(attributes: attrs)
      let c = UIGraphicsGetCurrentContext()!
      c.saveGState()
      // Translate the origin to the drawing location and rotate the coordinate system.
      c.translateBy(x: p.x, y: p.y)
      c.rotate(by: angle * .pi / 180)
      // Draw the text centered at the point.
      text.draw(at: CGPoint(x: -textSize.width / 2, y: -textSize.height / 2), withAttributes: attrs)
      // Restore the original coordinate system.
      c.restoreGState()
    }
    

提交回复
热议问题