Main.storyboard
ViewController.m
//
// ViewController.m
// 6A01.图片的裁剪(位图上下文)
//
// Created by huan on 16/1/29.
// Copyright © 2016年 huanxi. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//需求:从位图上下文,裁剪图片[裁剪成圆形,也添加圆形的边框],生成一张图片
//获取要裁剪的图片
UIImage *img = [UIImage imageNamed:@"papa"];
//1.开启位图上下文
UIGraphicsBeginImageContextWithOptions(img.size, NO, 0.0);
CGRect imgRect = CGRectMake(0, 0, img.size.width, img.size.height);
//1.1 获取当前位图上下文
#warning 在自定义的view的drawRect方法里,调用UIGraphicsGetCurrentContext获取的上下文,是图层上下文(Layeer Graphics Context)
CGContextRef bitmapContext = UIGraphicsGetCurrentContext();
//2.往位图上下文剪裁图片
//2.1 指定一个圆形的路径,把圆形之外的剪切掉
CGContextAddEllipseInRect(bitmapContext, imgRect);
CGContextClip(bitmapContext);
//2.2 添加图片
[img drawInRect:imgRect];
//2.3 添加边框
//设置边框的宽度
CGContextSetLineWidth(bitmapContext, 3);
//设置边框的颜色
[[UIColor blueColor] set];
CGContextAddEllipseInRect(bitmapContext, imgRect);
CGContextStrokePath(bitmapContext);
//3. 获取当前位图上下文的图片
UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
//4. 结束位图编辑
UIGraphicsEndImageContext();
//把图片显示在控制器的view
self.imgView.image = newImg;
//保存图片,先把图片转成NSData,然后调用其的write
NSData *imgData = UIImagePNGRepresentation(newImg);
[imgData writeToFile:@"/Users/huan/Desktop/new.png" atomically:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end