晚点的等待

博客园 首页 新随笔 联系 订阅 管理

09 - 给图片添加水印.

 给图片水印的目的:
 告诉别人图片的来源.
 防止别人盗用图片.打广告.

 添加水印它最终是生成了一个新的图片.
 生成图片要用到了图片上下文.不需要再去自定义View,
 之前一直在自定义View,是因为要拿跟View相关联的上下文.
 跟View相关联的上下文是系统自动帮我们创建的,所以不需要我们自己手动创建,
 但是图片上下文需要我们自己去手动创建.还需要我们自己手动去关闭.

 实现水印效果的思路:
 开启一个和原始图片一样的图片上下文.
 把原始图片先绘制到图片上下文.
 再把要添加的水印(文字,logo)等绘制到图片上下文.
 最后从上下文中取出一张图片.
 关闭图片上下文.

 1.如何开启一个图片上下文?
     size:开启多大的上文
     opaque:不透明度
     scale:缩放上下文.
     UIGraphicsBeginImageContextWithOptions(image.size, YES, 0);

 2.如何从图片上下文当中生成一张图片?
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

 3.如何关闭上下文?
    UIGraphicsEndImageContext();

代码实现:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载图片
    UIImage *image = [UIImage imageNamed:@"girl"];
    
    //开启一个位图上下文.(需要手动来开启)
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //先把原始图片绘制到上下文当中.
    [image drawAtPoint:CGPointZero];
    
    //要添加的内容
    NSString *str =  @"@My godess";
    //设置属性
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSFontAttributeName] = [UIFont systemFontOfSize:100];
    dict[NSForegroundColorAttributeName] = [UIColor blueColor];
    [str drawAtPoint:CGPointMake(1300, 1000) withAttributes:dict];
    //从上下文当中生成一张图片
   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭位图
    UIGraphicsEndImageContext();   
    //显示图片
    self.imageView.image = newImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

实现效果:

posted on 2015-12-09 22:25  晚点的等待  阅读(219)  评论(0)    收藏  举报