如何在不丢失 `foregroundColor` NSAttributedStringKey 的情况下设置 `strokeColor`?

How can I set `strokeColor` without losing `foregroundColor` NSAttributedStringKey?

有人说"Set minus value on strokeWidth",但它使字体变细。你有什么想法吗?

        let attributes: [NSAttributedStringKey : Any] = [
            .foregroundColor : UIColor.white,
            .strokeColor : UIColor.black,
            .strokeWidth : 2.0,
        ]

        label.attributedText = NSAttributedString(string: "Sample", attributes:attributes)

"Somebody say 'Set minus value on strokeWidth'" - 某人是 Apple itself:

This is because the sign of the value for NSStrokeWidthAttributeName is interpreted as a mode; it indicates whether the attributed string is to be filled, stroked, or both. Specifically, a zero value displays a fill only, while a positive value displays a stroke only. A negative value allows displaying both a fill and stroke.

您确实设置了一个负数 strokeWidth,但在小尺寸时效果不明显(iOS 11 默认字体大小为 14pt)。结合像素平滑,这使得字体看起来更细。这是 64pt 处负数 strokeWidth 的结果:

let attributes: [NSAttributedStringKey : Any] = [
    .foregroundColor : UIColor.white,
    .strokeColor : UIColor.black,
    .strokeWidth : -2,
    .font: UIFont.systemFont(ofSize: 64)
]
let text = NSAttributedString(string: "Sample", attributes:attributes)

strokeWidth: -5时的结果:

当您将 strokeWidth 设置得更深时,它看起来 "thicker" 但两者都不美观。我会留给你来决定你的应用程序的外观。