是否可以使用NSString UIKit添加来绘制带阴影的文本?

Cla*_*fou 13 uikit ios

使用NSString UIKit添加时,是否可以使用简单的文本阴影进行绘制?我的意思是无需编写代码,以两种颜色绘制两次,因为可以用各种UIKit类如的UILabel和其完成shadowColorshadowOffset性能,也没有做实际通过模糊的影子CGContextSetShadow(这是必然要贵得多).

Apple的这些扩展的文档实际上包括常量(在最底层)包含UITextAttributeTextShadowColor并且UITextAttributeTextShadowOffset暗示它是可能的,但我没有看到在实际方法中可能使用这些常量.

Rob*_*Rob 30

几点想法:

  1. 这些UITextAttributeTextShadow...键用于在使用文本属性字典时使用,例如,UIAppearance方法:

    NSDictionary *attributes = @{UITextAttributeTextShadowColor  : [UIColor blackColor],
                                 UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetMake(2.0, 0.0)],
                                 UITextAttributeTextColor        : [UIColor yellowColor]};
    
    [[UINavigationBar appearance] setTitleTextAttributes:attributes];
    
    Run Code Online (Sandbox Code Playgroud)

    这些UITextAttributeTextShadow...键仅用于接受文本属性字典的方法.

  2. 绘制文本字符串时最接近的等效键是使用带有NSShadowAttributeName键的属性字符串:

    - (void)drawRect:(CGRect)rect
    {
        UIFont *font = [UIFont systemFontOfSize:50];
    
        NSShadow *shadow = [[NSShadow alloc] init];
        shadow.shadowColor = [UIColor blackColor];
        shadow.shadowBlurRadius = 0.0;
        shadow.shadowOffset = CGSizeMake(0.0, 2.0);
    
        NSDictionary *attributes = @{NSShadowAttributeName          : shadow,
                                     NSForegroundColorAttributeName : [UIColor yellowColor],
                                     NSFontAttributeName            : font};
    
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:@"this has shadows" attributes:attributes];
    
        [attributedText drawInRect:rect];
    }
    
    Run Code Online (Sandbox Code Playgroud)

    但是,如果您担心能够执行贝塞尔曲线阴影的阴影算法的性能NSShadow损失,可能会受此影响.但做一些基准测试,改变shadowBlurRadius显着影响性能.例如,动画一个复杂的多行文本的旋转用shadowBlurRadius10.0一个缓慢的iPhone 3GS达到31 fps的帧速率,但改变shadowBlurRadius0.0得到60fps的帧速率.

    使用阴影模糊半径的底线0.0消除了贝塞尔生成的阴影的大部分(如果不是全部)计算开销.

  3. 仅供参考,我通过将blur值设置为0.0for 来体验类似的性能改进CGContextSetShadow,就像我在上面的归因文本再现中所经历的那样.

最重要的是,只要你使用模糊半径,我认为你不应该担心基于bezier的阴影的计算开销0.0.如果你自己两次写文本,一次为阴影再写一次前景色,我也不会感到惊讶,甚至可能会更有效率,但我不确定这些差异是否可以观察到.但我不知道任何API调用会为你做的(不是其他的CGContextSetShadowblur0.0).