Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
Piotr Tomasik Avatar asked Apr 16 '13 22:04

Piotr Tomasik


3 Answers

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)
like image 93
Piotr Tomasik Avatar answered Oct 08 '22 04:10

Piotr Tomasik


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)
like image 45
gvuksic Avatar answered Oct 08 '22 04:10

gvuksic


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

like image 2
Hari Narayanan Avatar answered Oct 08 '22 06:10

Hari Narayanan