当用户旋转场景/相机时,如何不旋转SCNSphere中的包装文本

时间:2018-10-19 02:21:15

标签: scenekit scnnode scnsphere

let dotGeometry = SCNSphere(radius: 0.0005)
let dotNode = SCNNode(geometry: dotGeometry)
dotNode.position = dotPosition
if let image = imageWithText(text: "\(index)", fontSize:20, imageSize: CGSize(width:100,height:100), backgroundColor: .cyan) {
    dotGeometry.firstMaterial?.diffuse.contents = image
}
self.rootNode.addChildNode(dotNode)

我正在使用以上代码创建具有SCNNode几何形状的SCNSphere,然后将其与使用以下代码创建的文本图像包装在一起:

除了用户开始旋转场景,球体随场景旋转以及文本移到用户视野之外的球体的背面之外,所有其他操作均有效。

func imageWithText(text:String, fontSize:CGFloat, 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 = [
        NSAttributedString.Key.font: UIFont(name: "Arial-BoldMT", size:fontSize),
        NSAttributedString.Key.paragraphStyle: paragraphStyle,
        NSAttributedString.Key.foregroundColor: fontColor
    ]

    // Determine the width/height of the text for the attributes
    let textSize = text.size(withAttributes: attributes as [NSAttributedString.Key : Any])

// 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 as [NSAttributedString.Key : Any])

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

如何使文本始终保持在用户的视野中,即不让文本随摄像机/场景旋转而旋转?

1 个答案:

答案 0 :(得分:0)

最后通过在创建dotNode.constraints = [SCNBillboardConstraint()]之后添加dotNode来完成此操作。