在 UIView 层 可以通过设置 layer 的 cornerRadius
来设置圆角。
也可通过 Layer 层设置 带圆角的maskLayer
来设置圆角。
那如果在 UIView 的 draw(rect)
方法中如何通过 CGContext 来绘制圆角了?
可以定义以下方法在 drawRect: 方法中调用
- (void)drawRoundRect:(CGRect)rect radius:(CGFloat)radius context:(CGContextRef)context {
float x1=rect.origin.x;
float y1=rect.origin.y;
float x2=x1+rect.size.width;
float y2=y1;
float x3=x2;
float y3=y1+rect.size.height;
float x4=x1;
float y4=y3;
CGContextMoveToPoint(context, x1, y1+radius);
CGContextAddArcToPoint(context, x1, y1, x1+radius, y1, radius);
CGContextAddArcToPoint(context, x2, y2, x2, y2+radius, radius);
CGContextAddArcToPoint(context, x3, y3, x3-radius, y3, radius);
CGContextAddArcToPoint(context, x4, y4, x4, y4-radius, radius);
CGContextClosePath(context);
}
CGContextAddArcToPoint
绘制圆弧的方法之一
void CGContextAddArcToPoint(CGContextRef c, CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius)
参数示意图如下:
P1 是当前路径所在的点,坐标是(x,y)
P1(x,y)和(x1,y1)构成切线1,(x1,y1)和(x2,y2)构成切线2, r 是上面函数中的radius, 红色的线就是CGContextAddArcToPoint绘制的曲线. 它不会画到 (x2, y2)这个点, 绘制到圆弧的终点就会停止.