我正在尝试从文本生成 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
, and CGColorSpaceCreateDeviceRGB
结果出现以下错误:
CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component color space; kCGImageAlphaLast; 448 bytes/row.
为了创建 OpenGL 想要的正确 RGBA8 格式,我缺少什么?
Update: 我改变了最后一个参数CGBitmapContextCreate
from kCGImageAlphaNone
(这是我复制粘贴代码时的情况)到kCGImageAlphaLast
,这是我错误尝试过的几种变体之一。
Update 2: UIGraphicsGetImageFromCurrentImageContext()
如果上下文不是用以下命令创建的,则返回 nilUIGraphicsBeginImageContext()
,因此需要以不同的方式提取图像:[UIImage imageWithCGImage:CGBitmapContextCreateImage(contextRef)]
.