How can I both stroke and fill with NSAttributedString w/ UILabel

Piotr Tomasik picture Piotr Tomasik · Apr 17, 2013 · Viewed 19.3k times · Source

Is it possible to apply both stroke and fill with an NSAttributedString and a UILabel?

Answer

Piotr Tomasik picture Piotr Tomasik · Apr 17, 2013

Yes, the key is to apply a Negative value to the NSStrokeWidthAttributeName If this value is positive you will only see the stroke and not the fill.

Objective-C:

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

Thanks to @cacau below: See also Technical Q&A QA1531

Swift 4 version:

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

label.attributedText = NSAttributedString(string: text, attributes: attributes)

Swift 5.1 version:

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

label.attributedText = NSAttributedString(string: text, attributes: attributes)