我正在使用 [NSString drawInRect:]
将文本绘制到纹理上,一切正常,直到我添加阴影。它们显示正确,但经常被我正在绘制的矩形剪裁。
问题是 [NSString sizeWithFont:]
不知道阴影,因为它们是通过 CGContextSetShadowWithColor(...)
应用的。
这是我正在使用的代码(已删除绒毛):
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];
我已经尝试扩展 dim
以考虑阴影和模糊,这大部分都有效,但有时由于额外的空间,扩展的 rect 导致行被完全不同地包裹添加。
有没有比我使用的更好的方法来找到绘制(或绘制字符串)所需的纹理/矩形的大小?
最佳答案
您只需要跟踪两个不同的矩形。
- 将包含您传递给
-[NSString drawInRect:]
的文本的矩形。调用此stringBounds
。 - 包含阴影的扩展/偏移矩形。调用此
shadowBounds
。
使您的纹理大小为 shadowBounds
。
绘制文本时,需要通过 shadowBounds.origin - stringBounds.origin
进行翻译。 (或者可能反过来——这完全取决于你做什么,按什么顺序。当你得到它时你就会知道。)
然后执行[theString drawInRect:stringBounds ...]
。
关于ios - NSString 绘制矩形 : and drop shadows on iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164808/