Swift - 描邊文字效果


項目需求,文字要有描邊效果,在這里記錄下來。 核心是使用NSAttributedString進行繪制。 建議將此方法寫在擴展中。另外還看到一些博主寫的描邊效果,其方式是繼承UILabel,然后重載drawTextInRect方法,我改成了Swift,在下面也一並附上,有興趣的可以看看

 overridefunc viewDidLoad() {
super.viewDidLoad()

let lab =UILabel(frame:view.bounds)
lab.attributedText =drawOutlineAttributedString(string:"哎呦,不錯哦", fontFloat:30, alignment: .center, textColor:UIColor.white, widthColor:UIColor.red)
view.addSubview(lab)
}

func drawOutlineAttributedString(string:String? =nil, fontFloat:CGFloat,
alignment: NSTextAlignment, textColor:UIColor,
widthColor: UIColor) ->NSAttributedString {

let paragraph =NSMutableParagraphStyle()
paragraph.alignment = alignment

let dic = [NSFontAttributeName:UIFont.systemFont(ofSize: fontFloat),
NSParagraphStyleAttributeName: paragraph,
NSForegroundColorAttributeName: textColor,
NSStrokeWidthAttributeName: (-1.5),
NSStrokeColorAttributeName: widthColor]as [String :Any]

var attributedText:NSMutableAttributedString!
if string !=nil{
attributedText = NSMutableAttributedString.init(string: string!, attributes: dic)
} else {
attributedText = NSMutableAttributedString.init(string:"", attributes: dic)
}
return attributedText
}

重載drawTextInRect方法

    overridefunc drawText(in rect: CGRect) {
let shadowOffset =self.shadowOffset
let textColor =self.textColor

let c =UIGraphicsGetCurrentContext()
c!.setLineWidth(1)
c!.setLineJoin(.round)
c!.setTextDrawingMode(.stroke)
self.textColor =UIColor.white
super.drawText(in: rect)

c!.setTextDrawingMode(.fill)
self.textColor = textColor
self.shadowOffset =CGSize(width: CGFloat(0), height:CGFloat(0))
super.drawText(in: rect)
self.shadowOffset = shadowOffset
}

效果如下:

 




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: