I’m trying to apply a rounded stroke effect to text using NSMutableAttributedString in Swift. I have been able to find various NSMutableAttributedString.Key options for text attributes like color, font, and underline, but I can’t seem to find any key that allows me to apply a rounded stroke to the text.
let attributes: [NSMutableAttributedString.Key: Any] = [
.font: font,
.strokeWidth: borderWidthToDraw,
.strokeColor: strokeColorToDraw,
]
For better visual support, expected & curent output has been .
2
Answers
The stroke border will be rounded if the font has rounded ends, such as SF Rounded.
Here I displayed an
NSAttributedString
in aUITextView
, using the SF Rounded font.Output:
This doesn’t look exactly the same as the picture in the question. If you want a rounded stroke but the text itself should be unrounded, I doubt you can do that with
NSAttributedString
alone. In the worst case, you might have to use CoreText functions likeCTFontCreatePathForGlyph
to get the paths of the glyphs, and changelineJoin
toround
.I doubt you can get your desired appearance using an attributed string.
If you’re open to another approach, here is an example using a
UILabel
subclass and overridingdrawText(...)
:Example controller:
Output:
Note: This
StrokeLabel
class is based on this answer: https://stackoverflow.com/a/69368542/6257435 with a few modifications.