首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SKLabel避免使用TextKit而不是创建SKTexture?

SKLabel避免使用TextKit而不是创建SKTexture?
EN

Stack Overflow用户
提问于 2016-11-07 18:27:33
回答 1查看 123关注 0票数 1

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

我问是因为我想做些更严肃的事.更大的间距,还有一些SKLabels不可能实现的东西,但它们是TextKit的一部分,但我希望它们成为位图,让它们看起来像我想要的那样。

但我找不到办法把TextKit变成图像。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-12 17:41:36

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

下面是来自这个GitHub项目的一个示例

代码语言:javascript
复制
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()
    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40472026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档