http://blog.csdn.net/casablaneca/article/details/23617069
![](https://img-blog.csdn.net/20140413204625718?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2FzYWJsYW5lY2E=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
在创建OpenGL场景时,我们常常需要在场景中渲染一些文字,如在游戏结束时,你需要显示一个“Game Over” 字样。 下面我在GLKit框架下写了一个方法,代码详细描述如下:
-
- -(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];
-
-
- 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.csdn.net/detail/luozhonglan/7187875