1.圆形图片
//图片裁剪
-(UIImage*)image:(UIImage*)image{
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
CGFloat radius = MIN(image.size.width, image.size.height)*0.5;
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, radius*2, radius*2)];
[path addClip];
[image drawAsPatternInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- 带边框的圆形图片裁剪
-(UIImage*)clipCircleWithBorder:(UIImage*)image{
//确定边框宽度
CGFloat borderWidth = 5;
//确定图片区域大小
CGFloat width = MIN(image.size.width, image.size.height);
//上下文尺寸
CGSize size = CGSizeMake(width+ borderWidth*2, width+borderWidth*2);
//开辟一个上下文
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
//绘制大圆,显示出来
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.width)];
[[UIColor blueColor]set];
[path fill];
//绘制小圆,裁剪路径
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth, borderWidth, width, width)];
[clipPath addClip];
[image drawAtPoint:CGPointMake(borderWidth, borderWidth)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- 截屏
-(UIImage*)clipScreen{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//保存图片到沙盒
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UIImage *image = [self clipScreen];
NSArray<NSString*> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString * path = [[paths lastObject]stringByAppendingPathComponent:@"2.png"];
NSLog(@"%@",path);
//把图片转成二进制流,可以做图片压缩(0到1),1表示原始质量,不压缩
//NSData *data = UIImageJPEGRepresentation(image, 1);//转成jpg
NSData *data = UIImagePNGRepresentation(image);//转成png
[data writeToFile:path atomically:YES];
}