主控制器关键代码:
ZRViewController.m
#import "MJViewController.h" #import "UIImage+ZR.h" @interface ZRViewController () @property (weak, nonatomic) IBOutlet UIImageView *iconView; @end @implementation ZRViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.返回水印图片 UIImage *newImage = [UIImage waterImageWithBg:@"scene" logo:@"logo"]; // 2.显示图片 self.iconView.image = newImage; }
创建UIImage分类文件:
UIImage+ZR.h
#import <UIKit/UIKit.h> @interface UIImage (ZR) /** * 打水印 * * @param bg 背景图片 * @param logo 右下角的水印图片 */ + (instancetype)waterImageWithBg:(NSString *)bg logo:(NSString *)logo; @end
UIImage+ZR.m
#import "UIImage+ZR.h" @implementation UIImage (ZR) + (instancetype)waterImageWithBg:(NSString *)bg logo:(NSString *)logo { UIImage *bgImage = [UIImage imageNamed:bg]; // 1.创建一个基于位图的上下文(开启一个基于位图的上下文) UIGraphicsBeginImageContextWithOptions(bgImage.size, NO, 0.0); // 2.画背景 [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width, bgImage.size.height)]; // 3.画右下角的水印 UIImage *waterImage = [UIImage imageNamed:logo]; CGFloat scale = 0.2; CGFloat margin = 5; CGFloat waterW = waterImage.size.width * scale; CGFloat waterH = waterImage.size.height * scale; CGFloat waterX = bgImage.size.width - waterW - margin; CGFloat waterY = bgImage.size.height - waterH - margin; [waterImage drawInRect:CGRectMake(waterX, waterY, waterW, waterH)]; // 4.从上下文中取得制作完毕的UIImage对象 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); // 5.结束上下文 UIGraphicsEndImageContext(); return newImage; } @end
原文:http://www.cnblogs.com/xuanzhangran123/p/5153946.html