NSString drawInRect: and drop shadows on iOS

依然范特西╮ 提交于 2019-12-11 08:22:47

问题


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.

  1. The rect that will contain the text, which you pass to -[NSString drawInRect:]. Call this stringBounds.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!