如何使用NSAttributedString w/UILabel来描边和填充

Pio*_*sik 37 cocoa nsattributedstring uilabel ios

是否可以应用笔划填充 a NSAttributedString和a UILabel

Pio*_*sik 85

是的,关键是要申请一个价值,NSStrokeWidthAttributeName 如果这个值是正的,你只会看到行程,而不是填充.

Objective-C的:

self.label.attributedText=[[NSAttributedString alloc] 
initWithString:@"string to both stroke and fill" 
attributes:@{
             NSStrokeWidthAttributeName: @-3.0,
             NSStrokeColorAttributeName:[UIColor yellowColor],
             NSForegroundColorAttributeName:[UIColor redColor]
             }
];
Run Code Online (Sandbox Code Playgroud)

感谢下面的@cacau:另见技术问答QA1531

Swift版本:

let attributes: [NSAttributedStringKey : Any] = [.strokeWidth: -3.0,
                                                 .strokeColor: UIColor.yellow,
                                                 .foregroundColor: UIColor.red]

label.attributedText = NSAttributedString(string: text, attributes: attributes)
Run Code Online (Sandbox Code Playgroud)

Swift 3版本:

let attributes: [NSAttributedString.Key : Any] = [.strokeWidth: -3.0,
                                                  .strokeColor: UIColor.yellow,
                                                  .foregroundColor: UIColor.red]

label.attributedText = NSAttributedString(string: text, attributes: attributes)
Run Code Online (Sandbox Code Playgroud)

Swift 4版本:

self.label.attributedText=[[NSAttributedString alloc] 
initWithString:@"string to both stroke and fill" 
attributes:@{
             NSStrokeWidthAttributeName: @-3.0,
             NSStrokeColorAttributeName:[UIColor yellowColor],
             NSForegroundColorAttributeName:[UIColor redColor]
             }
];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“轮廓”将是内部轮廓,而不是外部轮廓 - 即轮廓将侵蚀填充区域。 (2认同)
  • @Jason有没有办法用UILabel + AttributedText生成"外部"填充? (2认同)

gvu*_*sic 8

Swift版本:

let attributes = [NSStrokeWidthAttributeName: -3.0,
                      NSStrokeColorAttributeName: UIColor.yellowColor(),
                      NSForegroundColorAttributeName: UIColor.redColor()];

label.attributedText = NSAttributedString(string: "string to both stroke and fill", attributes: attributes)
Run Code Online (Sandbox Code Playgroud)

Swift 3版本:

    let attributes = [NSStrokeWidthAttributeName: -3.0,
                      NSStrokeColorAttributeName: UIColor.yellow,
                      NSForegroundColorAttributeName: UIColor.red] as [String : Any]

    label.attributedText = NSAttributedString(string: "string to both stroke and fill", attributes: attributes)
Run Code Online (Sandbox Code Playgroud)