Last active
April 25, 2020 08:16
-
-
Save ha1f/2f90e65cf722e1eed0df55c50bc5c9f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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