往UIImage上写字的四种方法

第一种方法

01.//Add text to UIImage 
02. 
03.-(UIImage *)addText:(UIImage *)img text:(NSString *)text1{ 
04. 
05.    int w = img.size.width; 
06. 
07.    int h = img.size.height;  
08. 
09.    //lon = h - lon; 
10. 
11.    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
12. 
13.    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); 
14. 
15.     
16.    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage); 
17. 
18.    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1); 
19. 
20.     
21.    char* text  = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];// "05/05/09"; 
22. 
23.    CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman); 
24. 
25.    CGContextSetTextDrawingMode(context, kCGTextFill); 
26. 
27.    CGContextSetRGBFillColor(context, 255, 255, 255, 1); 
28. 
29.     
30.  
31.    //rotate text 
32. 
33.    CGContextSetTextMatrix(context, CGAffineTransformMakeRotation( -M_PI/4 )); 
34. 
35.     
36.    CGContextShowTextAtPoint(context, 4, 52, text, strlen(text)); 
37. 
38.     
39.     
40.    CGImageRef imageMasked = CGBitmapContextCreateImage(context); 
41. 
42.    CGContextRelease(context); 
43. 
44.    CGColorSpaceRelease(colorSpace); 
45. 
46.     
47.    return [UIImage imageWithCGImage:imageMasked]; 
48. 
49.} 


第二种方法: 

01.-(UIImage *)imageFromText:(NSString *)text{     UIFont *font = [UIFont systemFontOfSize:20.0];        
02.CGSize size  = [text sizeWithFont:font];     UIGraphicsBeginImageContext(size);     CGContextRef ctx = UIGraphicsGetCurrentContext();      
03.// optional: add a shadow     
04. // optional: also, to avoid clipping you should make the context size bigger     CGContextSetShadowWithColor(ctx, CGSizeMake(2.0, -2.0), 5.0, [[UIColor grayColor] CGColor]);      
05.// draw in context      
06.[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];     
07.// transfer image      
08.UIImage *image = UIGraphicsGetImageFromCurrentImageContext();         
09.UIGraphicsEndImageContext();         
10.return image; 
11.} 

第三种方法: 

01.UIImage *myImage = loadUnwatermarkedImage();  
02.NSString *myWatermarkText = @"Watermark";  
03.UIImage *watermarkedImage = nil;  
04.  
05.UIGraphicsBeginImageContext(myImage.size);  
06.[myImage drawAtPoint: CGPointZero];  
07.[myWatermarkText drawAtPoint: CGPointMake(10, 10) withFont: [UIFont systemFontOfSize: 12]];  
08.watermarkedImage = UIGraphicsGetImageFromCurrentImageContext();  
09.UIGraphicsEndImageContext();  

第四种方法:

01.UIGraphicsBeginImageContext([parentView bounds].size); [[parentView layer] renderInContext:UIGraphicsGetCurrentContext()]; 
02.UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

http://blog.csdn.net/favormm/archive/2010/12/16/6081042.aspx

posted @ 2011-03-23 22:58  周宏伟  阅读(2923)  评论(0编辑  收藏  举报