本篇文章主要实现艺术字、给UILable添加内边距~
效果图如下:
代码如下:
var textInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
override func drawText(in rect: CGRect) {
//先描边填充
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(宽度)
context?.setLineJoin(.round)
context?.setTextDrawingMode(.fillStroke)
self.textColor = 颜色
super.drawText(in: rect.inset(by: textInsets))
//再描边
context?.setLineWidth(宽度)
context?.setLineJoin(.round)
context?.setTextDrawingMode(.stroke)
self.textColor = 颜色
super.drawText(in: rect.inset(by: textInsets))
//填充字体颜色
context?.setTextDrawingMode(.fill)
context?.setLineJoin(.round)
self.textColor = 颜色
super.drawText(in: rect.inset(by: textInsets))
}
//这里主要是用来增加UILabel的内边距
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insets = textInsets
var rect = super.textRect(forBounds: bounds.inset(by: insets),limitedToNumberOfLines: numberOfLines)
rect.origin.x -= insets.left
rect.origin.y -= insets.top
rect.size.width += (insets.left + insets.right)
rect.size.height += (insets.top + insets.bottom)
return rect
}