CoreText绘制水印
近期有同事拿别人手机打卡记录申述考勤异常,鉴于此,需要在考勤记录添加工号全图倾斜水印来防伪,在网上找了一些博客,都是使用老的方法直接在图片上绘制水印,都能实现需要的效果,但是其中使用的方法在iOS7已经废弃掉了,apple给的建议是使用CoreText来代替。(直接在图片绘制水印参见blog:http://blog.csdn.net/jiadabin/article/details/51669497)。接下来谈谈使用CoreText绘制水印。
1、创建一个继承自UIView的类,重写drawRect
- (void)drawRect:(CGRect)rect {
// Drawing code
[super drawRect:rect];
self.backgroundColor = [UIColor lightGrayColor];
// 得到当前用于绘制画布的上下文,用于后续将内容绘制在画布上
CGContextRef context = UIGraphicsGetCurrentContext();
//翻转当前的坐标系(因为对于底层绘制引擎来说,屏幕左下角为(0,0))
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//绘制背景图片
CGContextDrawImage(context, self.bounds, self.image.CGImage);
//创建绘制文字
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.waterText];
[attrString addAttribute:(id)kCTForegroundColorAttributeName value:[UIColor colorWithRed:31/255.0 green:233/255.0 blue:189/255.0 alpha:0.3] range:NSMakeRange(0, attrString.length)];
CGFloat fontSize = 18;
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialMT", fontSize, NULL);
[attrString addAttribute:(id)kCTFontAttributeName value:(__bridge id)fontRef range:NSMakeRange(0, attrString.length)];
CFRelease(fontRef);
//旋转画布
CGContextRotateCTM(context, 30*M_PI/180);
//根据NSAttributedString创建CTFramesetterRef
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
//获取绘制文字的尺寸
CGSize size = [attrString size];
//画布的长宽
int w = self.bounds.size.width;
int h = self.bounds.size.height;
//绘制文本行和列
int row = w/size.width;
int col = h/size.height;
//整个画布绘制文本
for (int i = 0; i<=row; i++) {;
for (int j = 0; j<=col; j++) {
//创建绘制区域CGPathRef
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake((size.width + 25) * i, j *(size.height + 20), size.width, size.height));
//根据CTFramesetterRef和CGPathRef创建CTFrame;
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attrString length]), path, NULL);
//绘制
CTFrameDraw(frame, context);
CFRelease(frame);
CFRelease(path);
}
}
CFRelease(frameSetter);
}
2、截取绘制View界面生成图片。
WaterLogoView *waterImageView = [[WaterLogoView alloc] initWithImage:[UIImage imageNamed:@"bg_dark"] waterText:@"123456"];
UIGraphicsBeginImageContext(CGSizeMake(kScreenWidth, kScreenHeight));
[waterImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
3、初始化UIImageView,使用上述生成的图片。
UIImageView *bgIV = [[UIImageView alloc] initWithFrame:self.view.bounds];
[bgIV setImage:viewImage];
4、把bgIV添加到当前视图View上。
[self.view addSubview:bgIV];