#import "ViewController.h" @interface ViewController () @end @implementation ViewController -(UIImage*)CircleImg { /*添加图片*/ UIImage* img = [UIImage imageNamed:@"J罗.jpg"]; CGFloat borderWith = 20.0f; CGSize imgSize = CGSizeMake(img.size.width + borderWith, img.size.height + borderWith); CGFloat bigRadius = imgSize.width * 0.5;/*外圆半径*/ CGFloat smallRadius = bigRadius - borderWith;/*内圆半径*/ UIGraphicsBeginImageContextWithOptions(imgSize, NO, 0.0f); CGContextRef ctx = UIGraphicsGetCurrentContext();/*得到图片的上下文*/ CGContextAddArc(ctx, bigRadius, bigRadius, bigRadius - borderWith / 2, 0, M_PI * 2, 0);/*添加大圆*/ CGContextSetStrokeColorWithColor(ctx, [[UIColor redColor] CGColor]); CGContextSetLineWidth(ctx, borderWith);/*设置线宽*/ CGContextStrokePath(ctx);/*画大圆*/ CGContextAddArc(ctx, bigRadius, bigRadius, smallRadius, 0, M_PI * 2, 0);/*添加小圆*/ CGContextClip(ctx);/*剪裁,后面的受影响*/ CGRect rect = CGRectMake(borderWith, borderWith, img.size.width, img.size.height); [img drawInRect: rect];/*画图*/ UIImage* img2 = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img2; } - (void)viewDidLoad { [super viewDidLoad]; /*用的是实际尺寸370,要不画出的border也会缩放*/ UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 370, 370)]; imgView.image = [self CircleImg]; [self.view addSubview:imgView]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
说是这个方法可扩展性高,比如添加个边框之类的。
注意大圆的半径,要减去边框的一半,否则边框显示不全。
参考:http://www.360doc.com/content/15/0128/17/20918780_444509231.shtml