I'm having trouble drawing an NSAttributedString
with no margins around it in its view. Here's my code:
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:72.0f]};
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"Hello"
attributes:attributes];
[string drawWithRect:rect
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesDeviceMetrics
context:nil];
This leads to the behavior below:
Note the margins at the left and top.
I realize that there may be ways to align text without making it meet the edges of the view, but making it meet the edges of the view will allow me to work with the view intuitively using autolayout and so on.
I do not care about the behavior when the string contains leading or trailing whitespace.
If this is not possible with NSAttributedString
, are there other ways to get this behavior that you'd recommend?
To clarify, here's what I want to see for number 1.
You can get the height,width vector values using CoreText:
double fWidth = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
size_t width = (size_t)ceilf(fWidth);
size_t height = (size_t)ceilf(ascent + descent + leading);
so you can get the rect. But the top margin is not wrong
Use CoreText, CTLineGetTypographicBounds() is probably what you are looking for. I haven't used this myself. The following code demonstrate the idea (drawing "Hello" to a custom UIView with no top/left margin).
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
UIGraphicsPushContext(context)
let viewHeight = bounds.size.height
let attributedString = NSAttributedString(string: "Hello")
let line = CTLineCreateWithAttributedString(attributedString)
var ascent: CGFloat = 0.0
let width = CTLineGetTypographicBounds(line, &ascent, nil, nil)
CGContextSaveGState(context)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0, -viewHeight)
CGContextSetTextPosition(context, 0, viewHeight - ascent)
CTLineDraw(line, context)
CGContextRestoreGState(context)
UIGraphicsPopContext()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With