最近项目中在做实名认证,要给图片添加水印,在网上找了一些博客,但是鱼龙混杂,首先说明下,有的博客说的方法实现了一下发现不可以。现在我就把我找的可以实现的几种方法贴在下边即可。以下方法我都亲自试过可以:
为了防止自己辛苦做的项目被别人盗走,采取图片添加水印,在此表示图片的独一无二。加水印不是在上面添加几个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;
}
/**
加半透明水印
@param useImage 需要加水印的图片
@param addImage1 水印不要传jpg类型图,支持png
@returns 加好水印的图片
*/
- (UIImage *)addImage:(UIImage *)useImage addMsakImage:(UIImage *)maskImage
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
{
UIGraphicsBeginImageContextWithOptions(useImage.size ,NO, 0.0); // 0.0 for scale means "scale for device's main screen".
}
#else
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0)
{
UIGraphicsBeginImageContext(useImage.size);
}
#endif
[useImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height)];
//四个参数为水印图片的位置
[maskImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height/2)];
[maskImage drawInRect:CGRectMake(0, useImage.size.height/2, useImage.size.width, useImage.size.height/2)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
下边还有两种方法:其中第一种还不支持中文,字符串不可传入中文,第二种logo水印的不支持jpg
- -(UIImage *)addText:(UIImage *)img text:(NSString *)text1
- {
- //上下文的大小
- int