so I have a UICollectionViewCell with a UIImage, and I'm trying to make the UIImage have a solid white background with text overlaid on top of it. I searched up how to do each of these separately and this is what I have:
Creating a UIImage with a solid color:
let rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let color = UIColor.white
color.setFill()
UIRectFill(rect)
let whiteImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Then I'm calling the function textToImage
with:
let textImage = textToImage(drawText: "Placeholder text", inImage: whiteImage, atPoint: CGPoint(x: 20.0, y: 20.0))
Where the textToImage
function is:
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.black
let textFont = UIFont(name: "Helvetica Neue", size: 74)
UIGraphicsBeginImageContext(image.size)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
And then setting textImage as the UIImage for a UICollectionViewCell.
The textToImage function works on a normal image, but if I try to create an image with a solid color first, then try to call textToImage on that newly created image, the solid color shows up but the text doesn't. Any advice on what could be the problem here? Thanks!