我正在尝试从文本生成一个RGBA8图像,用作OpenGL ES 2.0纹理。
+(UIImage *)imageFromText:(NSString *)text
{
UIFont *font = [UIFont systemFontOfSize:20.0];
CGSize size = [text sizeWithFont:font];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef contextRef = CGBitmapContextCreate (NULL,
size.width, size.height,
8, 4*size.width,
colorSpace,
kCGImageAlphaLast
);
CGColorSpaceRelease(colorSpace);
UIGraphicsPushContext(contextRef);
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsPopContext();
return image;
}
很遗憾,没有 CGColorSpaceCreateDeviceRGBA
,而使用 CGColorSpaceCreateDeviceRGB
将导致以下错误:
CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component color space; kCGImageAlphaLast; 448 bytes/row.
我该如何创建OpenGL所需的正确RGBA8格式?更新:我将CGBitmapContextCreate的最后一个参数从kCGImageAlphaNone(复制代码时的参数)更改为kCGImageAlphaLast,这是我尝试的几个变化之一。
更新2:如果上下文不是使用UIGraphicsBeginImageContext()创建的,则UIGraphicsGetImageFromCurrentImageContext()返回nil,因此需要以不同的方式提取图像:[UIImage imageWithCGImage:CGBitmapContextCreateImage(contextRef)]。
CGBitmapInfo
包括CGImageAlphaInfo
作为掩码的一部分。来自(https://developer.apple.com/library/ios/documentation/graphicsimaging/Reference/CGBitmapContext/Reference/reference.html#//apple_ref/c/func/CGBitmapContextCreate):“用于指定 alpha 通道信息的常量是使用CGImageAlphaInfo
类型声明的,但可以安全地传递给此参数。您还可以传递与CGBitmapInfo
类型相关联的其他常量。” - NSGod