建一個類目(不知道怎麼建的可以去百度一下) UIImage的類目
類目的.h文件 文件名為UIImage+watermark
#import
@interface UIImage (watermark)
//定義一個方法
- (UIImage *)watermarkImage:(NSString *)text;
@end
.m文件的實現
#import "UIImage+watermark.h"
@implementation UIImage (watermark)
- (UIImage *)watermarkImage:(NSString *)text{
//1.獲取上下文
UIGraphicsBeginImageContext(self.size);
//2.繪制圖片
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
//3.繪制水印文字
CGRect rect = CGRectMake(0, self.size.height-20, self.size.width, 20);
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
//文字的屬性
NSDictionary *dic = @{
NSFontAttributeName:[UIFont systemFontOfSize:13],
NSParagraphStyleAttributeName:style,
NSForegroundColorAttributeName:[UIColor whiteColor]
};
//將文字繪制上去
[text drawInRect:rect withAttributes:dic];
//4.獲取繪制到得圖片
UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();
//5.結束圖片的繪制
UIGraphicsEndImageContext();
return watermarkImage;
}
@end
然後再viewController 的視圖上添加一個UIImageView 導入類目(UIImage+watermark)文件
#import "ViewController.h"
#import "UIImage+watermark.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"baymax.jpg"];
//調用類目的方法實現功能
UIImage *img = [image watermarkImage:@"@大白"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
// imageView.frame = self.view.bounds;
[self.view addSubview:imageView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end