此文章為轉(zhuǎn)載剩檀, 原文地址: http://www.reibang.com/p/280dbe07d3fd
加水印的方式有很多限佩,比如給圖片添加圖片水印熊尉、文字水印,或者給視頻添加圖片水印锻狗、文字水印满力。本文首先講解如何給圖片添加文字水印、圖片水印轻纪,即圖文合成和圖片合成效果油额。
一、給圖片添加文字水印
// 給圖片添加文字水涌讨恪:+ (UIImage*)jx_WaterImageWithImage:(UIImage*)image text:(NSString*)text textPoint:(CGPoint)point attributedString:(NSDictionary* )attributed{//1.開啟上下文UIGraphicsBeginImageContextWithOptions(image.size,NO,0);//2.繪制圖片[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];//添加水印文字[text drawAtPoint:point withAttributes:attributed];//3.從上下文中獲取新圖片UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();//4.關(guān)閉圖形上下文UIGraphicsEndImageContext();//返回圖片returnnewImage;}
二潦嘶、給圖片添加圖片水印
給圖片添加圖片水印,這里提供兩種方法崇众,以供參考掂僵。
方法一:
// 給圖片添加圖片水印+ (UIImage*)jx_WaterImageWithImage:(UIImage*)image waterImage:(UIImage*)waterImage waterImageRect:(CGRect)rect{//1.獲取圖片//2.開啟上下文UIGraphicsBeginImageContextWithOptions(image.size,NO,0);//3.繪制背景圖片[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];//繪制水印圖片到當(dāng)前上下文[waterImage drawInRect:rect];//4.從上下文中獲取新圖片UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();//5.關(guān)閉圖形上下文UIGraphicsEndImageContext();//返回圖片returnnewImage;}
方法二:
1、新建類別UIImage+LL繼承自UIImage
/**
*? UIImage+LL.h
*/#import<UIKit/UIKit.h>@interfaceUIImage(LL)/**
*? 打水印
*
*? @param backgroundImage? 背景圖片
*? @param markName 右下角的水印圖片
*/+ (instancetype)waterMarkWithImageName:(NSString*)backgroundImage andMarkImageName:(NSString*)markName;@end
2顷歌、UIImage+LL.m中配置圖片合成的代碼
/**
*? UIImage+LL.m
*/#import"UIImage+LL.h"@implementationUIImage(LL)+ (instancetype)waterMarkWithImageName:(NSString*)backgroundImage andMarkImageName:(NSString*)markName{UIImage*bgImage = [UIImageimageNamed:backgroundImage];UIGraphicsBeginImageContextWithOptions(bgImage.size,NO,0.0);? ? [bgImage drawInRect:CGRectMake(0,0, bgImage.size.width, bgImage.size.height)];UIImage*waterImage = [UIImageimageNamed:markName];CGFloatscale =0.3;CGFloatmargin =5;CGFloatwaterW = waterImage.size.width * scale;CGFloatwaterH = waterImage.size.height * scale;CGFloatwaterX = bgImage.size.width - waterW - margin;CGFloatwaterY = bgImage.size.height - waterH - margin;? ? ? ? [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)];UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnnewImage;}@end
3锰蓬、背景圖片右下角添加水印圖片
/**
? ? ? ? *? 這個(gè)方法只需要傳入一個(gè)需要被打水印的圖片名字和一個(gè)水印圖標(biāo)的名字就可以自動(dòng)合成水印圖片
? ? ? ? */UIImage*image = [UIImagewaterMarkWithImageName:@"bg.jpeg"andMarkImageName:@"logo"];? ? ? ? _imageView.image = image;