Fork me on GitHub

往UIImage上写字的四种方法

第一种方法

//Add text to UIImage  

-(UIImage *)addText:(UIImage *)img text:(NSString *)text1{

int w = img.size.width;

int h = img.size.height;

//lon = h - lon;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);

CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];// "05/05/09";

CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman);

CGContextSetTextDrawingMode(context, kCGTextFill);

CGContextSetRGBFillColor(context, 255, 255, 255, 1);

//rotate text

CGContextSetTextMatrix(context, CGAffineTransformMakeRotation( -M_PI/4 ));

CGContextShowTextAtPoint(context, 4, 52, text, strlen(text));

CGImageRef imageMasked = CGBitmapContextCreateImage(context);

CGContextRelease(context);

CGColorSpaceRelease(colorSpace);

return [UIImage imageWithCGImage:imageMasked];

}



第二种方法: 

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



第三种方法: 

UIImage *myImage = loadUnwatermarkedImage();   
NSString *myWatermarkText = @"Watermark";
UIImage *watermarkedImage = nil;
UIGraphicsBeginImageContext(myImage.size);
[myImage drawAtPoint: CGPointZero];
[myWatermarkText drawAtPoint: CGPointMake(10, 10) withFont: [UIFont systemFontOfSize: 12]];
watermarkedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

 

第四种方法:

UIGraphicsBeginImageContext([parentView bounds].size);

[[parentView layer] renderInContext:UIGraphicsGetCurrentContext()];  

UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext(); 

posted on 2012-03-07 08:10  pengyingh  阅读(415)  评论(0)    收藏  举报

导航