Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active April 25, 2020 08:16
Show Gist options
  • Select an option

  • Save ha1f/2f90e65cf722e1eed0df55c50bc5c9f1 to your computer and use it in GitHub Desktop.

Select an option

Save ha1f/2f90e65cf722e1eed0df55c50bc5c9f1 to your computer and use it in GitHub Desktop.
extension UIImage {
/// 文字の画像を生成する。文字は中心に置かれる。
///
/// - parameter text: 文字列
/// - parameter font: フォント
/// - parameter textColor: 文字色
/// - parameter imageSize: 生成する画像のサイズ(スクリーンスケール倍される)
/// - returns: 生成されたテキスト画像
static func fromText(_ text: String, font: UIFont, textColor: UIColor, imageSize: CGSize) -> UIImage {
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: UIColor.dark80
]
let nsString = text as NSString
let textSize = nsString.size(withAttributes: attributes)
// 中心に置く
let textOrigin = CGPoint(
x: (imageSize.width - textSize.width) / 2,
y: (imageSize.height - textSize.height) / 2
)
let format = UIGraphicsImageRendererFormat.default().apply { format in
format.scale = UIScreen.main.scale
format.opaque = false
}
return UIGraphicsImageRenderer(size: imageSize, format: format).image { (context) in
nsString.draw(at: textOrigin, withAttributes: attributes)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment