標籤:
廢話不多說,直接上代碼
#import "ViewController.h"@interface ViewController ()@property (nonatomic,strong)UIImageView *imageView;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)]; [self.view addSubview:self.imageView]; [self yuan]; }/** * 在圓形外面加一個圓環 */- (void)yuanHuan{ //0.載入圖片 UIImage *image = [UIImage imageNamed:@"AppIcon1024"]; //圖片的寬度 CGFloat imageWH = image.size.width; //設定圓環的寬度 CGFloat border = 1; //大圓形的寬度高度 CGFloat ovalWH = imageWH + 2 * border; //1、開啟位元影像上下文 UIGraphicsBeginImageContextWithOptions(CGSizeMake(ovalWH, ovalWH), NO, 0); //2、畫大圓 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, ovalWH, ovalWH)]; [[UIColor redColor] set]; [path fill]; //3、設定裁剪區(小圓) UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(border, border, imageWH, imageWH)]; [clipPath addClip]; //4、繪製圖片 [image drawAtPoint:CGPointMake(border, border)]; //5、擷取圖片 UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext(); //6、關閉上下文 UIGraphicsEndImageContext(); self.imageView.image = clipImage;}/** * 裁剪一個原型圖片 */- (void)yuan{ //擷取圖片 UIImage *image = [UIImage imageNamed:@"AppIcon1024"]; //1.開啟位元影像上下文,跟圖片尺寸大小一樣 //NO:不透明 0:scale不縮放 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0); //2.設定圖形裁剪地區,正切圖片 //2.1建立一個圓形路徑 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.width)]; //2.2把路徑設定裁剪區 [path addClip]; //3.繪製圖片 [image drawAtPoint:CGPointMake(0, 0)]; //4.從上下文中擷取圖片 UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext(); //5.關閉上下文 UIGraphicsEndImageContext(); _imageView.image = clipImage; }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
源碼:https://github.com/TianHero/caijian.git
iOS圓形圖片裁剪,以及原型圖片外面加一個圓環