设计稿中常常要求实现圆角效果,这样才能体现mac ui的特色。NSView默认是尖角的,要想实现圆角效果,最直观的做法是,在xib文件的基础上,加一层layer,再设置layer的cornerRadius属性,代码如下:
self.view.wantsLayer = YES;
self.view.layer.cornerRadius = VIEW_RADIUS;
然而实践证明,上述使用xib的方式,并不能很好地达到预期。原有的尖角还是若隐若现,特别是在某些背景view的衬托下,就更加明显了。
行之有效的方法是,不用xib,自己实现view,并重写view的drawRect方法,利用Core Graphics(缩写CG)把圆角画出来,代码如下:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
CGContextRef context = [NSGraphicsContext currentContext].CGContext; // Core Graphics上下文,其实就是张画布
CGFloat minx = CGRectGetMinX(dirtyRect), midx = CGRectGetMidX(dirtyRect), maxx = CGRectGetMaxX(dirtyRect);
CGFloat miny = CGRectGetMinY(dirtyRect), midy = CGRectGetMidY(dirtyRect), maxy = CGRectGetMaxY(dirtyRect);
CGContextMoveToPoint(context, minx, midy); // 设置绘制起点为(minx, midy)
CGContextAddArcToPoint(context, minx, miny, midx, miny, VIEW_RADIUS); // 绘制view左下圆角
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, VIEW_RADIUS); // 绘制view右下圆角 CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, VIEW_RADIUS); // 绘制view右上圆角
CGContextAddArcToPoint(context, minx, maxy, minx, midy, VIEW_RADIUS); // 绘制view左上圆角
CGContextClosePath(context); CGContextSetFillColorWithColor(context, backGroundColor); //填充view的背景颜色
CGContextFillPath(context);}
绘制代码有些难以理解,具体参考如下链接:
http://stackoverflow.com/questions/8709794/when-drawing-an-arc-using-cgcontextaddarctopoint-what-does-x1-y1-and-x2-y2