在SceneKit中跨球体绘制文本

时间:2017-06-17 18:42:02

标签: ios text 3d scenekit scnnode

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

from BaseSpider import BaseSpider

我尝试使用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) 来实现我的需求,但我没有运气。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

您可以通过创建包含文本的图像(例如

)将文本环绕在对象的表面上

enter image description here

然后通过

加载并将图像分配给漫反射的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)

enter image description here

或者,您可以通过

以编程方式创建包含文本的图像
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)