NSString drawInRect:并在iOS上添加阴影 [英] NSString drawInRect: and drop shadows on iOS

查看:251
本文介绍了NSString drawInRect:并在iOS上添加阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用[NSString drawInRect:]将文本绘制到纹理上,并且一切正常,直到添加阴影为止.它们显示正确,但是经常被我要绘制的矩形剪裁.

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.

问题在于[NSString sizeWithFont:]不知道投影的阴影,因为它们是通过CGContextSetShadowWithColor(...)应用的.

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];

我尝试扩展dim来考虑阴影和模糊,并且大多数情况下都可行,但是有时扩展的rect会由于添加了额外的空间而使行的包裹方式完全不同.

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?

推荐答案

您只需要跟踪两个不同的rect.

You just need to keep track of two different rects.

  1. 将包含文本的矩形,您将其传递给-[NSString drawInRect:].称为stringBounds.
  2. 包含阴影的扩展/偏移矩形.称为shadowBounds.
  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.

使纹理的大小为shadowBounds.

绘制文本时,需要按shadowBounds.origin - stringBounds.origin进行翻译. (或者可能是相反的情况,这取决于您的工作确切,以什么顺序进行.一旦获得,您就会知道的.)

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.)

然后[theString drawInRect:stringBounds ...].

这篇关于NSString drawInRect:并在iOS上添加阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆