iOS开发-给图片添加水印

为了防止自己辛苦做的项目被别人盗走,采取把图片添加水印,在此表示图片的独一无二。加水印不是要在上面添加上几个Label,而是我们要把字画到图片上成为一个整体,下面这篇文章主要介绍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;
    
    UIGraphicsBeginImageContextimg.size);
    
    [img drawInRect:CGRectMake0,0, w, h)];
    
    NSDictionary *attr = @{
                           
                           NSFontAttributeName: [UIFont boldSystemFontOfSize:10],  //设置字体
                           
                           NSForegroundColorAttributeName : [UIColor blackColor]   //设置字体颜色
                           
                           };
    
//    [mark drawInRect:CGRectMake, , , ) withAttributes:attr];         //左上角
//    
//    [mark drawInRect:CGRectMakew - , , , ) withAttributes:attr];      //右上角
//    
//    [mark drawInRect:CGRectMakew - , h - - , , ) withAttributes:attr];  //右下角
    
    [mark drawInRect:CGRectMake50, 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:CGRectMake0, 0, self.size.width, self.size.height)]; 
 //水印图 
 [mask drawInRect:rect]; 
 UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext); 
 UIGraphicsEndImageContext); 
 return newPic; 
}

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注