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

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


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)

Swift version:

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

label.attributedText = NSAttributedString(string: "string to both stroke and fill", attributes: attributes)

Swift 3 version:

    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)

Now Latest in swift apple remove the [String: Any] for attributes key value declaration use as [NSAttributedStringKey : Any]

    let strokeTextAttributes = [
        NSAttributedStringKey.strokeColor : UIColor.green,
        NSAttributedStringKey.foregroundColor : UIColor.lightGray,
        NSAttributedStringKey.strokeWidth : -4.0,
        NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 52)
        ] as [NSAttributedStringKey : Any]

    hello_cell_lb.attributedText = NSAttributedString(string: "\(hello_array[indexPath.row])", attributes: strokeTextAttributes)

thank you