Search code examples
iosuikitnsattributedstring

NSAttributedString drawInRect disappears when the frame is offset


I have a very strange problem. When I offset my frame/rect which I use to draw my NSAttributedString

My text disappears. Any ideas why? Here is the image with an simple offset of 40 px.

r.size = [self.text boundingRectWithSize:r.size
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                     context:nil].size;
    r.origin.y +=40;
    [[UIColor orangeColor] setFill];
    CGContextFillRect(ctx, r);
    [self.text drawInRect:r];

Result:

enter image description here

And here is without the offset. enter image description here

How do I draw the AttributedText at a given offset?


Solution

  • I don't know why this question has not yet been addressed. This is a serious issue with the NSAttributedString API that I hope Apple acknowledges soon, either in documentation or by patching the implementation.

    For the time being, you can work around the issue by translating the graphics context before drawing your string.

    CGContextRef context = whatever;
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, x, y);
    // draw here
    CGContextRestoreGState(context);