iOS 上的NSAttributedString阴影和描边?

8

当我使用描边和阴影时,会出现某种双重描边的情况。我该如何解决这个问题?

示例代码:

import UIKit

var shadow = NSShadow()
shadow.shadowColor = UIColor.black
shadow.shadowOffset = CGSize(width: 0, height: 3)

class CustomLabel: UILabel {
    override func drawText(in rect: CGRect) {
        let attributes: [String: Any] = [NSStrokeWidthAttributeName: -2.0,
                          NSStrokeColorAttributeName: UIColor.black,
                          NSForegroundColorAttributeName: UIColor.white,
                          NSShadowAttributeName: shadow,
                          NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: 50)]
        self.attributedText = NSAttributedString(string: self.text ?? "", attributes: attributes)
        super.drawText(in: rect)
    }
}

let label = CustomLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
label.backgroundColor = UIColor.orange
label.text = "Hello"

结果:

在这里输入图片描述


该图片无法直接解释,需要更多的上下文来理解它所代表的意思。
1个回答

8

我弄清楚了。如果我对标签的CALayer应用阴影并禁用背景颜色,它就可以按预期工作:

import UIKit

class CustomLabel: UILabel {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 0, height: 3)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 0.0
    }

    override func drawText(in rect: CGRect) {
        let attributes: [String: Any] = [NSStrokeWidthAttributeName: -2.0,
                                         NSStrokeColorAttributeName: UIColor.black,
                                         NSForegroundColorAttributeName: UIColor.white,
                                         NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: 50)]
        self.attributedText = NSAttributedString(string: self.text ?? "", attributes: attributes)
        super.drawText(in: rect)
    }
}

let label = CustomLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
label.text = "Hello"

enter image description here


太棒了!感谢分享! - Vlad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接