iOS:图片添加水印

来源:互联网 发布:晨曦预算软件 编辑:程序博客网 时间:2024/06/08 17:31

图片添加水印简单的理解就是将图片和文字绘制在一张图片内。值得注意的是,图片大小各异,即使添加相同样式的水印,也会在查看图片的时候,使水印看起来大小不一。为了解决这个问题,需要把图片按屏幕宽度重绘,水印添加的位置也需要是相对重绘后的图片的位置。

具体实现如下:

- (UIImage *)imageAddWaterMark:(NSString *)mark{    //针对屏幕重置图片大小    CGFloat ratio = self.size.height/self.size.width;    CGFloat width = [UIScreen mainScreen].bounds.size.width;    CGFloat height = width*ratio;    //绘制到画布中    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, [[UIScreen mainScreen] scale]);    [self drawInRect:CGRectMake(0, 0, width, height)];    //转换成富文本    NSRange range = NSMakeRange(0,[mark length]);    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:mark];    //水印右对齐    NSMutableParagraphStyle *stype = [[NSMutableParagraphStyle alloc] init];    stype.alignment = NSTextAlignmentRight;    [attributedString addAttribute:NSParagraphStyleAttributeName value:stype range:range];    //水印颜色    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];    //水印字体    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:9] range:range];    //水印位置    CGRect rect = CGRectMake(-5, height-25, width, 25);    [attributedString drawInRect:rect];    //获取水印后的图片    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return newImage;}

创建UIImage的类别,如:UIImage+Category.h,即可直接使用。

NOTE
如果需要像新浪微博一样,添加的图片和文字水印,可使用富文本中的NSTextAttachment。

0 0
原创粉丝点击