IOS给图片添加水印(两种方式)
为了防止自己辛苦做的项目被别人盗走,采取图片添加水印,在此表示图片的独一无二。加水印不是在上面添加几个Label,而是我们把字画到图片上成为一个整体,下面小编给大家分享IOS给图片添加水印(两种方式)。
提供一个方法,此方法只需要传递一个要加水印的图片和水印的内容就达到效果。
第一种方式:
-(UIImage*)watermarkImage:(UIImage*)imgwithName:(NSString*)name
{
NSString*mark=name;
intw=img.size.width;
inth=img.size.height;
UIGraphicsBeginImageContext(img.size);
[imgdrawInRect:CGRectMake(,,w,h)];
NSDictionary*attr=@{
NSFontAttributeName:[UIFontboldSystemFontOfSize:],//设置字体
NSForegroundColorAttributeName:[UIColorredColor]//设置字体颜色
};
[markdrawInRect:CGRectMake(,,,)withAttributes:attr];//左上角
[markdrawInRect:CGRectMake(w-,,,)withAttributes:attr];//右上角
[markdrawInRect:CGRectMake(w-,h--,,)withAttributes:attr];//右下角
[markdrawInRect:CGRectMake(,h--,,)withAttributes:attr];//左下角
UIImage*aimg=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnaimg;
}
第二种方式:用drawInRect很方便,图片、文字都可以加
//画水印
-(UIImage*)imageWithWaterMask:(UIImage*)maskinRect:(CGRect)rect
{
#if__IPHONE_OS_VERSION_MAX_ALLOWED>=40000
if([[[UIDevicecurrentDevice]systemVersion]floatValue]>=4.0)
{
UIGraphicsBeginImageContextWithOptions([selfsize],NO,0.0);//0.0forscalemeans"scalefordevice'smainscreen".
}
#else
if([[[UIDevicecurrentDevice]systemVersion]floatValue]<4.0)
{
UIGraphicsBeginImageContext([selfsize]);
}
#endif
//原图
[selfdrawInRect:CGRectMake(0,0,self.size.width,self.size.height)];
//水印图
[maskdrawInRect:rect];
UIImage*newPic=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnnewPic;
}
以上叙述用两种方式实现IOS给图片添加水印,需要的朋友可以来参考下,希望大家能够喜欢。