//开启/获取/关闭上下文的用UIGraphics...
//配置上下文的用CGcontext...
1.图像添加logo
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *oldImage = [UIImageimageNamed:@"img.png"];
//1.开启上下文
//opaque不透明,YES-不透明,NO-透明
UIGraphicsBeginImageContextWithOptions(oldImage.size,NO, 0.0);
[oldImage drawAtPoint:CGPointZero];
NSString *text =@"我要升官发财";
NSDictionary *dict =@{
NSFontAttributeName:[UIFontsystemFontOfSize:15],//字体大小
NSForegroundColorAttributeName:[UIColorredColor]//字体颜色
};
[text drawAtPoint:CGPointMake(110,160) withAttributes:dict];
//2.从当前图像上下文获取新图像(加了logo的)
UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();
//3.关闭上下文
UIGraphicsEndImageContext();
//显示
_imageView.image = newImage;
//保存新图像到桌面 ·
//1.将图片转换为png格式的二进制数据
NSData *data =UIImagePNGRepresentation(newImage);
//2.写入桌面
[data writeToFile:@"/Users/cuihao/Desktop/newImage.png"atomically:YES];
}
2.
awakeFromNib比drawRect要早,是加载storyboard或xib后执行
drawRect //当视图显示的时候,就会调用,默认是调用一次
[selfsetNeedsDisplay];//重绘,调用drawRect
3.
//保存图片
- (void)saveDraw{
//开启上下文
UIGraphicsBeginImageContextWithOptions(self.bounds.size,NO, 0.0);
//获取当前上下文
CGContextRef ctx =UIGraphicsGetCurrentContext();
//把画板上的内容渲染到上下文
[self.layerrenderInContext:ctx];
//获取当前上下文的图片
UIImage *captureImage =UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
// //保存图片
// NSData *data = UIImagePNGRepresentation(captureImage);
// [data writeToFile:@"/Users/cuihao/Desktop/image.png" atomically:YES];
// 保存到用户的相册里面
UIImageWriteToSavedPhotosAlbum(captureImage,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);//不是保存在mac的相册而是iPhone的相册里
}
// 保存相册后回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error) {// 保存失败
[MBProgressHUDshowError:@"保存失败"];
}else{// 保存成功
[MBProgressHUDshowSuccess:@"保存成功"];
}
}
4.当类不满足使用的时候,可以用继承的办法,扩展更多的属性和方法