问题描述
我需要在我的 Metal 应用中渲染一些文本。与其手动操作,不如使用 Apple 的文本渲染 API。
在一个简单的空窗口的 drawRect
中调用此代码打印字符串:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:26],NSFontAttributeName,[NSColor blackColor],NSForegroundColorAttributeName,nil];
NSAttributedString * s = [[NSAttributedString alloc] initWithString:@"Hello!"
attributes: attributes];
[s drawAtPoint:NSMakePoint(300,300)];
但这在具有 Metal 视图的窗口中不起作用。我猜一切都被冲淡了?
有可能吗?与在 Metal 视图顶部显示按钮 (NSButton) 相同。
谢谢。
解决方法
有可能,但并不简单。您需要将 drawViewHierarchyInRect
与 UILabel
或 UIButton
一起使用,并传递从 CVPixelBufferRef
创建的上下文。从那里,您需要使用金属 API 将 CVPixelBufferRef
链接到金属纹理,然后您可以正常绘制。我不建议每帧都这样做。
如果您需要一些用金属渲染的精美 UI,可能有更好的选择,或者您可以在金属视图顶部的 UIView 中渲染标签、按钮等。
您的文本需要在 3D 世界中还是在 2D 中叠加?