羅大柚OpenGL ES教程系列_LessonY_使用2D紋理渲染文字




在創建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.csdn.net/detail/luozhonglan/7187875


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章