创建 category
.h
#import <UIKit/UIKit.h>
@interface UIImage (ImageCircle)
-(UIImage *)ImageClipCircle;
@end
.m
#import "UIImage+ImageCircle.h"
@interface view : UIView
@property(nonatomic,strong)UIImage *image;
@end
@implementation view
-(void)drawRect:(CGRect)rect{
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//开始需改状态
CGContextSaveGState(ctx);
//绘制圆形
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, rect.size.width/2, rect.size.height/2));
//圆圈裁剪出来
CGContextClip(ctx);
//添加路径
CGContextFillPath(ctx);
//图片绘制
[_image drawAtPoint:CGPointMake(0, 0)];
//恢复状态
CGContextRestoreGState(ctx);
}
@end
@implementation UIImage (ImageCircle)
-(UIImage *)ImageClipCircle{
//我们绘制的圆是UIView,通过上下文等将其转化成UIImage
CGFloat ImageSizeMin = MIN(self.size.width, self.size.height);
CGSize imageSize = CGSizeMake(ImageSizeMin, ImageSizeMin);
view *mview = [[view alloc]init];
mview.image = self;
//开始绘制
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
mview.frame = CGRectMake(0, 0, ImageSizeMin, ImageSizeMin);
mview.backgroundColor =[UIColor whiteColor];
[mview.layer renderInContext:context];
UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext();
//结束绘制
UIGraphicsEndImageContext();
return imageNew;
}
@end
在ViewController中
- (void)viewDidLoad {
[super viewDidLoad];
[self imageCircle];
}
-(void)imageCircle{
UIImage *image =[UIImage imageNamed:@"1"];
UIImage *imageNew =[image ImageClipCircle];
UIImageWriteToSavedPhotosAlbum(imageNew, nil, nil, nil); //保存图片到手机相册
}
添加 <key>NSPhotoLibraryUsageDescription</key> <string>App需要您的同意,才能访问相册</string> iOS 10如果访问必须添加否则闪退