向 drawRect 中的 NSString 文本添加阴影:不使用 UILabel 的方法 [英] Adding a drop shadow to NSString text in a drawRect: method without using UILabel
问题描述
我想为使用 iOS 提供的 NSString (UIStringDrawing)
类别方法绘制的文本添加阴影:
I'd like to add a drop shadow to text drawn using the iOS supplied NSString (UIStringDrawing)
category method:
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width
withFont:(UIFont *)font minFontSize:(CGFloat)minFontSize
actualFontSize:(CGFloat *)actualFontSize
lineBreakMode:(UILineBreakMode)lineBreakMode
baselineAdjustment:(UIBaselineAdjustment)baselineAdjustment;
显然,没有阴影选项.
是的,可以在这里使用 UILabel 并设置投影属性,但这不会那么高效,因为任何 UIView 子类(例如 UILabel)都包装了一个 CALayer 对象并且会更重(性能明智).
Yes, one could use a UILabel here and get drop shadow properties to set, but that wouldn't be as performant, since any UIView subclass (such as UILabel) wraps a CALayer object and is going to be heavier (performance wise).
这是上下文:
我正在为 UITableViewCell 子类进行自定义绘图,在表格单元格视图上实现 drawRect:
而不是从复合 UIView 子类的 Nib 文件创建表格单元格.
I'm doing custom drawing for a UITableViewCell subclass, implementing drawRect:
on the table cell view instead of creating the table cell from a Nib file of composited UIView subclasses.
组合一堆 UIView 子类将无法保持这种精简并在表格视图滚动性能上保持在每秒 50-60 帧之内.
Compositing a bunch of UIView subclasses would defeat the purpose of trying to keep this lean and stay within 50-60 frames per second in table view scrolling performance.
我曾尝试以轻微的偏移量绘制字符串两次.一旦我在我要去的单元格的背景颜色上调整阴影颜色,这可能会变得可以接受,但它似乎相当笨拙.当然没有像 UILabel 那样的阴影模糊属性.
I have tried drawing the string twice at a slight offset. This may turn out acceptable once I tweak the drop shadow color on the background color of the cell that I have going, but it seems rather kludgey. Certainly there's no drop shadow blur property like one gets with UILabel.
我搜索了解决方案,他们要么推荐使用 UILabel(我已经在上面驳回了,因为我有大约十几个不同的文本元素被合成到表格单元格视图中)或 CGContextSetShadow()
.后者似乎总是在矩形的上下文中被建议,而不一定用于将阴影附加到使用上面提到的 NSString drawAtPoint...
方法直接绘制的文本路径.(我确实尝试过,但似乎没有用(即没有任何变化);我是 Core Graphics 绘图的新手.
I searched for solutions and they either recommend UILabel usage (which I've dismissed per above, since I have about a dozen distinct textual elements getting composited on to the table cell view) or CGContextSetShadow()
. The latter always seems to be suggested in the context of rectangular shapes, and not necessarily for attaching a shadow to the path of text drawn directly with the NSString drawAtPoint...
method mentioned above. (I did try it, but it didn't seem to work (i.e. nothing changed); I'm new to Core Graphics drawing).
建议?
推荐答案
CGContextSetShadow()
对我来说效果很好.示例:
It works fine for me with CGContextSetShadow()
. Example:
- (void)drawRect:(CGRect)rect
{
NSString *string = @"Hello World!";
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShadow(context, CGSizeMake(20.0f, 20.0f), 10.0f);
[string drawAtPoint:CGPointMake(100.0f, 100.0f) withFont:[UIFont boldSystemFontOfSize:36.0f]];
}
这篇关于向 drawRect 中的 NSString 文本添加阴影:不使用 UILabel 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!