在创建OpenGL场景时,我们常常需要在场景中渲染一些文字,如在游戏结束时,你需要显示一个“Game Over” 字样。 下面我在GLKit框架下写了一个方法,代码详细描述如下:
//用文字作为image
-(UIImage *) imageWithText:(NSString *)text
fontName:(NSString *)fontName
color:(UIColor *)color
width:(float)width
height:(float)height
rightAlign:(BOOL) rightAlign
{
CGRect textRect = [text boundingRectWithSize:CGSizeMake(width, height)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:60.0]}
context:nil];
CGSize expectedLabelSize = textRect.size;
float offsetX = rightAlign ? (width - expectedLabelSize.width) : 0.0f;
UIImage *image2 = [[UIImage alloc] init];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 1);
[image2 drawInRect:CGRectMake(offsetX,
expectedLabelSize.height / 2.0,
expectedLabelSize.width,
expectedLabelSize.height)
blendMode:kCGBlendModeNormal
alpha:1.0f];
[image2 drawAtPoint:CGPointMake(offsetX, 0.0f)];
[text drawAtPoint:CGPointMake(offsetX,0.0f)
withAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:36.0],
NSForegroundColorAttributeName: color}];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
然后,按照下面的方式调用上述方法:
UIImage *image = [self imageWithText:@"齐天大圣到此一游" fontName:@"Helvetica" color:[UIColor greenColor] width:300.0 height:100.0 rightAlign:YES];
//设置纹理
CGImageRef imageRef = [image CGImage];
//接受一个CGImgaeRef并创建一个新的包含CGImageRef的像素数据的OpenGL ES 纹理缓存
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:imageRef options:nil error:NULL];
self.effect.texture2d1.name = textureInfo.name;
self.effect.texture2d1.target = textureInfo.target;
由于用2D纹理绘制文字的原理比较简单,只需要看懂
-(UIImage *) imageWithText:(NSString *)text
fontName:(NSString *)fontName
color:(UIColor *)color
width:(float)width
height:(float)height
rightAlign:(BOOL) rightAlign
方法就OK,整个十分方便。
最后是源码下载地址: http://download.youkuaiyun.com/detail/luozhonglan/7187875