Outline UILabel text in UILabel Subclass

后端 未结 6 1897
你的背包
你的背包 2020-12-31 09:52

I\'m trying hard to find a way to simply add an outline/stroke/contour to my UILabel text. Talking about a stroke around the letters of the text not around the background of

6条回答
  •  一整个雨季
    2020-12-31 10:33

    @anandnimje answer converted to Swift 4.2 and wrapped it into a function:

    public func stroke(font: UIFont, strokeWidth: Float, insideColor: UIColor, strokeColor: UIColor) -> [NSAttributedStringKey: Any]{
        return [
            NSAttributedStringKey.strokeColor : strokeColor,
            NSAttributedStringKey.foregroundColor : insideColor,
            NSAttributedStringKey.strokeWidth : -strokeWidth,
            NSAttributedStringKey.font : font
            ]
    }
    

    Usage:

    label.attributedText = NSMutableAttributedString(string: "Hello World", 
    attributes: stroke(font: UIFont(name: "SourceSansPro-Black", size: 20)!, 
    strokeWidth: 4, insideColor: .white, strokeColor: .black))
    

    Make sure you have the right name for your UIFont, else it crashes. Should never be a problem if you have the right name.

提交回复
热议问题