iOS开发TipsiOS 开发每天分享优质文章Swift

iOS给图片添加文字水印和图片水印

2017-04-26  本文已影响3163人  金丝楠

加水印的方式有很多,比如给图片添加图片水印、文字水印,或者给视频添加图片水印、文字水印。本文首先讲解如何给图片添加文字水印、图片水印,即图文合成和图片合成效果。

一、给图片添加文字水印

// 给图片添加文字水印:
+ (UIImage *)jx_WaterImageWithImage:(UIImage *)image text:(NSString *)text textPoint:(CGPoint)point attributedString:(NSDictionary * )attributed{
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //2.绘制图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //添加水印文字
    [text drawAtPoint:point withAttributes:attributed];
    //3.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //4.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}

二、给图片添加图片水印

给图片添加图片水印,这里提供两种方法,以供参考。

方法一

// 给图片添加图片水印
+ (UIImage *)jx_WaterImageWithImage:(UIImage *)image waterImage:(UIImage *)waterImage waterImageRect:(CGRect)rect{
    
    //1.获取图片
    
    //2.开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //3.绘制背景图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //绘制水印图片到当前上下文
    [waterImage drawInRect:rect];
    //4.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //5.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}

方法二

1、新建类别UIImage+LL继承自UIImage

/**
 *  UIImage+LL.h
 */
#import <UIKit/UIKit.h>

@interface UIImage (LL)
/**
 *  打水印
 *
 *  @param backgroundImage   背景图片
 *  @param markName 右下角的水印图片
 */
+ (instancetype)waterMarkWithImageName:(NSString *)backgroundImage andMarkImageName:(NSString *)markName;
@end

2、UIImage+LL.m中配置图片合成的代码

/**
 *  UIImage+LL.m
 */
#import "UIImage+LL.h"

@implementation UIImage (LL)

+ (instancetype)waterMarkWithImageName:(NSString *)backgroundImage andMarkImageName:(NSString *)markName{
    
    UIImage *bgImage = [UIImage imageNamed:backgroundImage];
    
    UIGraphicsBeginImageContextWithOptions(bgImage.size, NO, 0.0);
    [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width, bgImage.size.height)];
    
    UIImage *waterImage = [UIImage imageNamed:markName];
    CGFloat scale = 0.3;
    CGFloat margin = 5;
    CGFloat waterW = waterImage.size.width * scale;
    CGFloat waterH = waterImage.size.height * scale;
    CGFloat waterX = bgImage.size.width - waterW - margin;
    CGFloat waterY = bgImage.size.height - waterH - margin;
    
    [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
@end

3、背景图片右下角添加水印图片

        /**
         *  这个方法只需要传入一个需要被打水印的图片名字和一个水印图标的名字就可以自动合成水印图片
         */
        UIImage *image = [UIImage waterMarkWithImageName:@"bg.jpeg" andMarkImageName:@"logo"];

        _imageView.image = image;

4、效果图如下

加水印之图片合成.png
上一篇下一篇

猜你喜欢

热点阅读