0

I want to render an NSString to a monochrome OpenGL texture. I found many examples on how to to that on iOS, but I'm struggling to find a code snippet that works on OSX.

I know how to do the last bit, uploading a texture to the GPU, but how do I get the raw (8 bit per pixel) data?

4

1 回答 1

2

查看Apple 的Cocoa OpenGL 代码示例中的GLString.m。您可以轻松修改它以生成单色纹理。相关修改导致代码如下所示:

NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:frameSize.width pixelsHigh:frameSize.height
    bitsPerSample:8 samplesPerPixel:1 hasAlpha:NO isPlanar:NO colorSpaceName:NSDeviceWhiteColorSpace bitmapFormat:0 bytesPerRow:frameSize.width bitsPerPixel:8];

NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];

…    

[string drawAtPoint:NSMakePoint(marginSize.width, marginSize.height)]; // draw at offset position

…

[NSGraphicsContext restoreGraphicsState];

if (0 == texName)
    glGenTextures (1, &texName);

glBindTexture (GL_TEXTURE_RECTANGLE_EXT, texName);
glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, 0, 0, texSize.width, texSize.height, GL_LUMINANCE, GL_UNSIGNED_BYTE, [bitmap bitmapData]);

关键部分是:

  1. 使用所需的格式分配您自己的 NSBitmapImageRep。
  2. 分配一个 NSGraphicsContext 写入您的 NSBitmapImageRep。
  3. 画出你的绳子。
  4. 将图形上下文恢复到其原始状态。
  5. 使用与您初始化 NSBitmapImageRep 的格式兼容的像素格式调用 glTexSubImage2D。
于 2013-01-19T20:35:18.903 回答