往UIImage上写字的四种方法

本文介绍了在iOS开发中给图片添加水印的四种不同方法。第一种方法使用Core Graphics绘制旋转的文字水印;第二种方法展示如何从纯文本创建图片;第三种方法通过直接在图片上下文中绘制文字实现水印效果;最后一种方法则是通过渲染UIView来获取包含水印的最终图片。

第一种方法

//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(); 

转载于:https://www.cnblogs.com/pengyingh/articles/2382940.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值