Created
June 28, 2024 09:46
-
-
Save Adobels/e7682bce150efe56e033d4d82c3f5522 to your computer and use it in GitHub Desktop.
generateImageOfLetterInRectangleOfSize
This file contains 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
public static func generateImageOfLetterInRectangleOfSize( | |
letter: Character, | |
backgroundColor: UIColor, | |
letterColor: UIColor, | |
width: CGFloat, | |
height: CGFloat | |
) -> UIImage { | |
let size = CGSize(width: width, height: height) | |
let renderer = UIGraphicsImageRenderer(size: size) | |
let image = renderer.image { context in | |
backgroundColor.setFill() | |
context.fill(CGRect(origin: .zero, size: size)) | |
let attributes: [NSAttributedString.Key: Any] = [ | |
.foregroundColor: letterColor, | |
.font: UIFont.systemFont(ofSize: min(width, height) / 2), // Adjust the font size to fit the rectangle | |
] | |
let letterString = String(letter) | |
let textSize = letterString.size(withAttributes: attributes) | |
let textRect = CGRect( | |
x: (size.width - textSize.width) / 2, | |
y: (size.height - textSize.height) / 2, | |
width: textSize.width, | |
height: textSize.height | |
) | |
letterString.draw(in: textRect, withAttributes: attributes) | |
} | |
return image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment