iOS:图片添加水印

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

具体实现如下:

- (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。

猜你喜欢

转载自blog.csdn.net/liuq0725/article/details/70808381