ios 文字带边框Label,文字边框

158 阅读1分钟

/// 文字带边框
class TQCountLabel: UILabel {
    var strokeLineWidth: CGFloat = 5
    var strokeLineColor: UIColor = UIColor.white

    private var textInsets: UIEdgeInsets {
        UIEdgeInsets(top: strokeLineWidth,
                     left: strokeLineWidth,
                     bottom: strokeLineWidth,
                     right: strokeLineWidth)
    }

    override func drawText(in rect: CGRect) {
        let fillTextColor = textColor
        let textShadowOffset = shadowOffset

        let content = UIGraphicsGetCurrentContext()
        content?.setLineWidth(strokeLineWidth)
        content?.setLineJoin(.round)
        content?.setTextDrawingMode(.stroke)
        textColor = strokeLineColor
        super.drawText(in: rect.inset(by: textInsets))

        content?.setTextDrawingMode(.fill)
        textColor = fillTextColor
        shadowOffset = .zero
        super.drawText(in: rect.inset(by: textInsets))

        shadowOffset = textShadowOffset
    }

    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
    }
}