I'm trying to draw text using CoreText
. I have the following code:
guard let context = UIGraphicsGetCurrentContext() else { return }
let attrString = NSAttributedString(string: "Str")
let path = CGMutablePath()
// Commented code does work, why?
// path.addRect(CGRect(x: 0, y: 50, width: attrString.size().width + 1, height: attrString.size().height + 1))
path.addRect(CGRect(x: 0, y: 50, width: attrString.size().width, height: attrString.size().height))
let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)
CTFrameDraw(frame, context)
Why does increasing the size of CGRect
help, while the actual size of NSAttributedString
doesn't?
Any help is appreciated.
When working with an attributed string and getting its size, you need to at least specify a font. The size of "Str"
will be quite different with an 8 point font versus a 72 point font, for example.
It might also help to convert the calculated CGRect
into an integral rect which will round up any fractional sizes. Use the integral
property of CGRect
.