为了防止自己辛苦做的项目被别人盗走,采取把图片添加水印,在此表示图片的独一无二。加水印不是要在上面添加上几个Label,而是我们要把字画到图片上成为一个整体,下面这篇文章主要介绍IOS给图片添加水印,有需要的小伙伴可以来参考下

方法一:水印为文字

效果如图:

iOS开发-给图片添加水印-编程知识网

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageVIew;
@property (weak, nonatomic) IBOutlet UITextField *markName;
@property (weak, nonatomic) IBOutlet UIImageView *resultImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (IBAction)getResultImage {
    
    self.resultImageView.image = [self watermarkImage:self.imageVIew.image withName:self.markName.text];
    
    
}


/**
 *  照片加水印
 *
 *  @param img  需要加水印的照片
 *  @param name 需要加上去的文字
 *
 *  @return 加好文字的照片
 */
-(UIImage *)watermarkImage:(UIImage *)img withName:(NSString *)name

{
    
    NSString* mark = name;
    
    int w = img.size.width;
    
    int h = img.size.height;
    
    UIGraphicsBeginImageContext(img.size);
    
    [img drawInRect:CGRectMake(0,0, w, h)];
    
    NSDictionary *attr = @{
                           
                           NSFontAttributeName: [UIFont boldSystemFontOfSize:10],  //设置字体
                           
                           NSForegroundColorAttributeName : [UIColor blackColor]   //设置字体颜色
                           
                           };
    
//    [mark drawInRect:CGRectMake(, , , ) withAttributes:attr];         //左上角
//    
//    [mark drawInRect:CGRectMake(w - , , , ) withAttributes:attr];      //右上角
//    
//    [mark drawInRect:CGRectMake(w - , h - - , , ) withAttributes:attr];  //右下角
    
    [mark drawInRect:CGRectMake(50, h - 20 , 100, 20) withAttributes:attr];    //左下角
    
    UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return aimg;
    
}

方法二:水印为图片

// 画水印 
- (UIImage *) imageWithWaterMask:(UIImage*)mask inRect:(CGRect)rect 
{ 
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 
 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) 
 { 
 UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen". 
 } 
#else 
 if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0) 
 { 
 UIGraphicsBeginImageContext([self size]); 
 } 
#endif 
 //原图 
 [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; 
 //水印图 
 [mask drawInRect:rect]; 
 UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext(); 
 UIGraphicsEndImageContext(); 
 return newPic; 
}