在SceneKit中跨球体绘制文本
我刚开始在我的UIKit应用程序中使用SceneKit,目的是显示和操作一些3D模型。我需要展示一个包含一些简短文字的球体。我渲染领域是这样的:在SceneKit中跨球体绘制文本
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
实现我需要什么,但我有一点运气。什么是正确的方法来做到这一点?
可以通过创建包含文本的图像,例如包裹的物体的表面周围的文本,
,然后加载和通过
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)
分配图像到漫的
contents
属性
或者,您可以通过编程方式创建一个i通过
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)
出色地工作!谢谢! –
当要显示的文本的属性被指定时,是否有办法使它将文本呈现为HTML?我正在为UILabel做一些类似的设置'documentType'属性的自定义'setHTML'方法。 –
我找不到任何可以让你做到的事情。也许你可以用'NSAttributedString'完成相同或类似的事情。 – 0x141E
适用于球? – 0x141E
@ 0x141E基本上是的,我需要它成为球体表面的一部分 –