0

使用 Swift 5、iOS 14

我将这段代码放在一起,使用 UIGraphicsImageRenderer 将文本写入图像。

它有效,但我想知道我是否在这里混合了旧的和新的。有没有更好的方法来做到这一点,而不是使用 NSAttributedStrings,它肯定会在未来一两年内被淘汰。

func returnTile(text: String) -> UIImage {
  let renderer = UIGraphicsImageRenderer(size: CGSize(width: 64, height: 128))
  return renderer.image { (context) in
    context.cgContext.setStrokeColor(UIColor.white.cgColor)
    context.stroke(CGRect(x: 0, y: 0, width: 64, height: 128))

    let attributes = [
      NSAttributedString.Key.font : UIFont.preferredFont(forTextStyle: .body),
      NSAttributedString.Key.foregroundColor : UIColor.white
    ]
    text.draw(in: CGRect(x: 32, y: 64, width: 64, height: 128), withAttributes: attributes)
    }
  }
4

0 回答 0