2

I am trying to add a stroke to a UILabel text in Swift. This is the text I have used:

var congratsLabel = UILabel(frame: CGRectMake(10, popUpView.frame.size.height * 0.540, popUpView.frame.size.width, 70))
congratsLabel.font = UIFont(name: Font.Daydreamer, size: 70)
congratsLabel.text = "Snap!"
congratsLabel.numberOfLines = 0
congratsLabel.textColor = UIColor.whiteColor()
congratsLabel.textAlignment = NSTextAlignment.Center
popUpView.addSubview(congratsLabel)

I have also tried using the NSMutableAttributedString althoough it is coming out a bit ropey and not how I want, the code I used for that also was:

var String = "Snap!"

var strokeString = NSMutableAttributedString(string: String, attributes: [NSFontAttributeName:UIFont(name: Font.Daydreamer, size: 70.0)!])
strokeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSRange(location:0,length:5))
strokeString.addAttribute(NSStrokeColorAttributeName, value: UIColor.blackColor(), range:  NSRange(location: 0, length: 5))
strokeString.addAttribute(NSStrokeWidthAttributeName, value: 1, range: NSRange(location: 0, length: 5))

This is the look I am trying to recreate.

enter image description here

But it is coming out like this (The backgrounds are different) but as you can see the stroke is taking over the entire word:

enter image description here

Alladinian
  • 34,483
  • 6
  • 89
  • 91
Henry Brown
  • 2,219
  • 8
  • 31
  • 48
  • Could you show what's your current render? You should use the `NSAttributedString` version. But we can't guess from your code what's wrong. – Larme May 07 '15 at 19:54
  • I have edited. The problem is that the stroke is suffocating the entire word leaving no room for the actual word in the middle – Henry Brown May 07 '15 at 20:05
  • 1
    Try to put first a negative value to `NSStrokeWidthAttributeName` value. Like -1 (and try to find the correct value: -2, -3, etc.). – Larme May 07 '15 at 20:07
  • No that still doesn't work, same outcome...? – Henry Brown May 07 '15 at 20:19
  • http://stackoverflow.com/questions/4467597/how-do-you-stroke-the-outside-of-an-nsattributedstring – Larme May 07 '15 at 20:39
  • @HenryBrown Larme is right. A negative stroke will enable _both_ stroke & fill (where a positive value only a stroke and a transparent fill - that's why it is not visible in your example). I have just tried it with a couple of fonts in a playground and works fine... – Alladinian May 07 '15 at 21:09
  • And regarding your comment (the stroke is suffocating the entire word...), that's right... maybe a two-step solution like a slightly bigger copy with a large black stroke behind the text could achieve the desired effect. – Alladinian May 07 '15 at 21:17
  • Thanks for all your help. It was actually your idea @Alladinian with putting a layer behind the text that has the best result. Thanka! – Henry Brown May 08 '15 at 18:46

0 Answers0