我正在尝试创建具有轮廓的文本。我目前正在将 SKLabelNode 与 NSAttributedString 一起使用,从 iOS 11 开始,您现在可以在 SpriteKit 中执行此操作。问题是,如果笔划宽度太粗,则轮廓会被 SKLabelNode 的边界矩形切断。请参阅下面的图像和代码。
extension SKLabelNode {
func addStroke(_ strokeColor:UIColor) {
let font = UIFont(name: self.fontName!, size: self.fontSize)
let attributes:[NSAttributedStringKey:Any] = [.strokeColor: strokeColor, .strokeWidth: 20.0, .font: font!]
let attributedString = NSMutableAttributedString(string: " \(self.text!) ", attributes: attributes)
let label1 = SKLabelNode()
label1.horizontalAlignmentMode = self.horizontalAlignmentMode
label1.text = self.text
label1.zPosition = -1
label1.attributedText = attributedString
self.addChild(label1)
}
}
我查看了扩展用作边框文本的 SKLabelNode 的框架,但这是一个只获取属性。我试图添加前导/尾随空格,但它们似乎被自动修剪了。为 strokeWidth 使用负值有效但会创建一个内部笔划,我更喜欢有一个外部笔划。
有什么想法吗?先谢谢您的帮助! 迈克
最佳答案
- 您不需要为笔划创建单独的节点。
- 使用负宽度值只渲染没有填充的笔画。
- 使用
.foregroundColor
填充。 - 您应该首先检查属性字符串是否已经存在,以确保您不会破坏它。
代码如下:
extension SKLabelNode {
func addStroke(color:UIColor, width: CGFloat) {
guard let labelText = self.text else { return }
let font = UIFont(name: self.fontName!, size: self.fontSize)
let attributedString:NSMutableAttributedString
if let labelAttributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
let attributes:[NSAttributedStringKey:Any] = [.strokeColor: color, .strokeWidth: -width, .font: font!, .foregroundColor: self.fontColor!]
attributedString.addAttributes(attributes, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
关于swift - SKLabelNode 边界和边界问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407034/