I need to render some text in my Metal app. Rather then doing it manually, I'd like to use Apple's text rendering API.
Calling this code in a simple empty window's drawRect
prints the string:
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)];
But this doesn't work in a window with a Metal view. I guess everything gets flushed?
Is it possible? And the same thing with displaying a button (NSButton) on top of a Metal view.
Thanks.
It is possible, but not simple. You will need to use drawViewHierarchyInRect
with UILabel
or UIButton
, and pass a context created from a CVPixelBufferRef
. From there, you need to use metal api's to link the CVPixelBufferRef
to a metal texture, which you can then draw as normal. I would not recommend doing this every frame.
If you need some fancy UI that is rendered with metal, there are probably better alternatives, or you can just render your labels, buttons, etc. inside a UIView on top of your metal view.
Does your text need to be in the 3D world or is it overlay on top in 2D?