问题
I'm using [NSString drawInRect:]
to draw text to a texture and everything works fine until I add drop shadows. They appear correctly, but are often clipped by the rect I'm drawing to.
The issue is that [NSString sizeWithFont:]
doesn't know about the drop shadows since they are applied via CGContextSetShadowWithColor(...)
.
Here is the code I'm using (fluff removed):
CGSize dim = [theString sizeWithFont:uifont];
...
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f);
CGContextTranslateCTM(context, 0.0f, dim.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
CGContextSetShadowWithColor(context, CGSizeMake(dropOffset.x, dropOffset.y), dropBlur, dropColorRef);
...
[theString drawInRect:dim withFont:uifont lineBreakMode:UILineBreakModeWordWrap alignment:align];
I've tried expanding dim
to take the drop shadow and blur into account and that mostly works, but sometimes the expanded rect causes the line to be wrapped completely different due to the extra space that was added.
Is there a better way to be finding the size of the texture/rect needed to draw to (or to draw the string) than I'm using?
回答1:
You just need to keep track of two different rects.
- The rect that will contain the text, which you pass to
-[NSString drawInRect:]
. Call thisstringBounds
. - The expanded/offset rect that contains the shadow. Call this
shadowBounds
.
Make your texture the size of shadowBounds
.
When you draw the text, you'll need to translate by shadowBounds.origin - stringBounds.origin
. (Or possibly the reverse -- it depends on exactly what you do, in which order. You'll know it when you get it.)
Then do [theString drawInRect:stringBounds ...]
.
来源:https://stackoverflow.com/questions/10164808/nsstring-drawinrect-and-drop-shadows-on-ios