The foregroundColor in attributes doesn't take a cgColor
context.cgContext.setFillColor(UIColor.black.cgColor) not needed use UIColor.black.setFill() instead.
Final changes
let imageSize = CGSize(width: 400, height: 100)
let testRenderer = UIGraphicsImageRenderer(size: imageSize)
let testImage = testRenderer.image { context in
UIColor.black.setFill()
context.fill(CGRect(origin: .zero, size: imageSize))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 8.0),
.paragraphStyle: paragraphStyle,
.foregroundColor: UIColor.white]
var attributedString = NSAttributedString(string: "This is some text",
attributes: attributes)
let drawContext = NSStringDrawingContext()
drawContext.minimumScaleFactor = 0.5
attributedString.draw(with: testRenderer.format.bounds, options: .usesLineFragmentOrigin,
context: drawContext)
}
-enjoy!