在SceneKit中跨球体绘制文本

3

我刚开始在我的UIKit应用程序中使用SceneKit,旨在显示和操作一些3D模型。我需要显示一个球体,并在其上写入一些简短的文本。我正在这样渲染球体:

let sphereGeometry = SCNSphere(radius: 1)
let sphereNode = SCNNode(geometry: sphereGeometry)
sphereNode.position = SCNVector3(x: -1, y: 0, z: 8)
sphereGeometry.firstMaterial?.diffuse.contents = UIColor.cyan

self.rootNode.addChildNode(sphereNode)

我尝试使用CATextLayer来实现我需要的效果,但是一直没有成功。请问正确的方法是什么?


你想让文本环绕球体吗? - 0x141E
@0x141E 基本上是的,我需要它成为球体表面的一部分。 - Youssef Moawad
1个回答

10

您可以通过创建包含文本的图像,例如 这个示例,将文本环绕在对象表面周围,然后加载并将该图像分配给漫反射属性的contents属性。

    let sphereGeometry = SCNSphere(radius: 1)
    let sphereNode = SCNNode(geometry: sphereGeometry)
    sphereNode.position = SCNVector3(x: 0, y: 0, z: 0)

    if let textImage = UIImage(named:"TextImage") {
        sphereGeometry.firstMaterial?.diffuse.contents = textImage
    }

    scene.rootNode.addChildNode(sphereNode)

在此输入图片描述

或者您可以通过编程创建带有文本的图像来实现

func imageWithText(text:String, fontSize:CGFloat = 150, fontColor:UIColor = .black, imageSize:CGSize, backgroundColor:UIColor) -> UIImage? {

    let imageRect = CGRect(origin: CGPoint.zero, size: imageSize)
    UIGraphicsBeginImageContext(imageSize)

    defer {
        UIGraphicsEndImageContext()
    }

    guard let context = UIGraphicsGetCurrentContext() else {
        return nil
    }

    // Fill the background with a color
    context.setFillColor(backgroundColor.cgColor)
    context.fill(imageRect)

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center

    // Define the attributes of the text
    let attributes = [
        NSFontAttributeName: UIFont(name: "TimesNewRomanPS-BoldMT", size:fontSize),
        NSParagraphStyleAttributeName: paragraphStyle,
        NSForegroundColorAttributeName: fontColor
    ]

    // Determine the width/height of the text for the attributes
    let textSize = text.size(attributes: attributes)

    // Draw text in the current context
    text.draw(at: CGPoint(x: imageSize.width/2 - textSize.width/2, y: imageSize.height/2 - textSize.height/2), withAttributes: attributes)

    if let image = UIGraphicsGetImageFromCurrentImageContext() {
        return image
    }
    return nil
}

并将图片应用到球体上

    let sphereGeometry = SCNSphere(radius: 1)
    let sphereNode = SCNNode(geometry: sphereGeometry)
    sphereNode.position = SCNVector3(x: 0, y: 0, z: 0)

    if let image = imageWithText(text: "Hello, World!", imageSize: CGSize(width:1024,height:1024), backgroundColor: .cyan) {
        sphereGeometry.firstMaterial?.diffuse.contents = image
    }

    scene.rootNode.addChildNode(sphereNode)

1
工作得非常出色!谢谢! - Youssef Moawad
当指定要显示的文本属性时,是否有一种方法可以使其呈现为HTML格式?我正在为UILabel执行类似操作,使用自定义的setHTML方法设置documentType属性。 - Youssef Moawad
我找不到任何可以让你这样做的东西。也许你可以通过使用“NSAttributedString”来实现相同或类似的功能。 - 0x141E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接