·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> IOS给图片添加水印(两种方式)

IOS给图片添加水印(两种方式)

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

为了防止自己辛苦做的项目被别人盗走,采取图片添加水印,在此表示图片的独一无二。加水印不是在上面添加几个Label,而是我们把字画到图片上成为一个整体,下面小编给大家分享IOS给图片添加水印(两种方式)。

提供一个方法,此方法只需要传递一个要加水印的图片和水印的内容就达到效果。

第一种方式:

-(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(, , w, h)];
 
   NSDictionary *attr = @{
 
              NSFontAttributeName: [UIFont boldSystemFontOfSize:],  //设置字体
 
              NSForegroundColorAttributeName : [UIColor redColor]   //设置字体颜色
 
              };
 
   [mark drawInRect:CGRectMake(, , , ) withAttributes:attr];         //左上角
 
   [mark drawInRect:CGRectMake(w - , , , ) withAttributes:attr];      //右上角
 
   [mark drawInRect:CGRectMake(w - , h - - , , ) withAttributes:attr];  //右下角
 
   [mark drawInRect:CGRectMake(, h - - , , ) withAttributes:attr];    //左下角
 
   UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
 
   UIGraphicsEndImageContext();
 
   return aimg;
 
 }

第二种方式:用drawInRect很方便,图片、文字都可以加

// 画水印 
- (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; 
} 

以上叙述用两种方式实现IOS给图片添加水印,需要的朋友可以来参考下,希望大家能够喜欢。