gpt4 book ai didi

swift - SKLabel 避免,使用 TextKit 而不是创建 SKTexture?

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:30 25 4
gpt4 key购买 nike

留在 SpriteKit 中,是否可以使用 TextKit 提供的更强大的控制创建更多“艺术”文本,然后(以某种方式)将这些字符串转换为图像以便它们可以用作 SKSpriteNode?

我问是因为我想做一些更严肃的字距调整……更大的间距,以及其他一些 SKLabels 无法实现的东西,但它们是 TextKit 的一部分,但我希望它们能够一旦我完成让它们看起来像我想要的方式,就成为位图。

但我找不到将 A TextKit 转换为图像的方法。

最佳答案

您可以在 CGContext 中绘制文本,然后从中创建纹理并将该纹理分配给 SKSpriteNode

这是来自 this GitHub project 的示例:

class ASAttributedLabelNode: SKSpriteNode {

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

init(size: CGSize) {
super.init(texture: nil, color: UIColor.clear, size: size)
}

var attributedString: NSAttributedString! {
didSet {
draw()
}
}

func draw() {
guard let attrStr = attributedString else {
texture = nil
return
}

let scaleFactor = UIScreen.main.scale
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(data: nil, width: Int(size.width * scaleFactor), height: Int(size.height * scaleFactor), bitsPerComponent: 8, bytesPerRow: Int(size.width * scaleFactor) * 4, space: colorSpace, bitmapInfo: bitmapInfo) else {
return
}

context.scaleBy(x: scaleFactor, y: scaleFactor)
context.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
UIGraphicsPushContext(context)

let strHeight = attrStr.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil).height
let yOffset = (size.height - strHeight) / 2.0
attrStr.draw(with: CGRect(x: 0, y: yOffset, width: size.width, height: strHeight), options: .usesLineFragmentOrigin, context: nil)

if let imageRef = context.makeImage() {
texture = SKTexture(cgImage: imageRef)
} else {
texture = nil
}

UIGraphicsPopContext()
}

}

关于swift - SKLabel 避免,使用 TextKit 而不是创建 SKTexture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com