Skip to content

Instantly share code, notes, and snippets.

@Adobels
Created June 28, 2024 09:46
Show Gist options
  • Save Adobels/e7682bce150efe56e033d4d82c3f5522 to your computer and use it in GitHub Desktop.
Save Adobels/e7682bce150efe56e033d4d82c3f5522 to your computer and use it in GitHub Desktop.
generateImageOfLetterInRectangleOfSize
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