I'm creating a thing that puts text on top of images. The biggest allowed frame for the text to be drawn is specified by our backend, and I have to do my best to fit whatever text the user enters into that rectangle.
I looked up a ton of older answers, but all answers seem to either use UILabel
automatic fitting or just brute forcing String.boundingRect(with:options:attributes:context:)
.
My initial idea was to just divide use the height of the text rectangle as the point size, but this seems to not work 100% in addition to not supporting text's that will be too long horizontally.
Here's how I'm drawing stuff right now, just to get some context.
let image = renderer.image { context in
backgroundImage.draw(at: .zero)
let titleAttributes: [NSAttributedStringKey: Any] = [
.font: UIFont(name: fontName, size: maxSize.height)!,
.foregroundColor: UIColor.white,
.paragraphStyle: NSMutableParagraphStyle(alignment: alignment),
.shadow: NSShadow( color: .black, offset: .zero, radius: 28),
]
(title as NSString).draw(with: maxFrame,
options: .usesLineFragmentOrigin,
attributes: titleAttributes,
context: nil)
}
Is there any efficient way to figure out the point size of a font to fit inside a rectangle without using UILabels or brute forcing it?