使用iOS核心图形绘制空心圆
我正在寻找如何在iOS中使用核心图形(使用iOS核心图形绘制空心圆,ios,objective-c,core-graphics,cgcontext,Ios,Objective C,Core Graphics,Cgcontext,我正在寻找如何在iOS中使用核心图形(CGContext)绘制空心圆的方法。我尝试使用以下代码执行此操作: - (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(ctx, 8.0); CGContextSetStrokeColor(ctx, CGCol
CGContext
)绘制空心圆的方法。我尝试使用以下代码执行此操作:
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 8.0);
CGContextSetStrokeColor(ctx, CGColorGetComponents([[UIColor redColor] CGColor]));
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillEllipseInRect(ctx, rect);
CGContextFillPath(ctx);
}
但它画出了一个完整的圆圈。
因为这个问题在这里讨论得太多了,但是其他的例子如只给我填充的圆。如果你只想要圆的轮廓,不要填充它
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 8.0);
[[UIColor redColor] set];
CGContextStrokeEllipseInRect(ctx, rect);
}
使用
CGContextStrokeEllipseInRect
而不是CGContextFillEllipseInRect
。由于您还没有在当前上下文中构建路径,因此可以摆脱CGContextFillPath
一种方法,即绘制一个填充圆,然后使用CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeClear)绘制一个稍小的圆。
在代码之后添加如下内容
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 5.0);
CGContextSetBlendMode(ctx,kCGBlendModeClear)
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillEllipseInRect(ctx, rect);
CGContextFillPath(ctx);
UIGraphicsEndImageContext();
我在绘图应用程序中使用
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeClear)
,这可能是更好的用法。笔划路径可能适合您。如果您想使用笔划方法和rect in参数在rect内绘制一个圆,您将在rect外绘制一部分圆
然后,假设您知道要绘制的圆的宽度,您有两个选择
首先,您可以绘制直线,但必须以较小的矩形绘制:
-(void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat innerWidth = 8;
[[UIColor redColor] setStroke];
CGContextSetLineWidth(ctx, innerWidth);
// We add an ellipsis shifted by half the inner Width
CGContextAddEllipseInRect(ctx, CGRectInset(rect, innerWidth, innerWidth));
// Stroke the path
CGContextStrokePath(ctx);
}
也可以使用奇偶规则()填充圆
你说的空圆圈是什么意思?就像一个看不见的圆或一个在圆周围有笔划但中空的圆?“中空”,感谢您的更正,我将编辑标题。这是一个有价值的替代想法,因为笔划椭圆实际上会将一半笔划画在预期圆之外,而填充、插入、,然后再次填充将使生成的图形完全包含在内。但是,您的代码并不能实现您所说的功能。
-(void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat innerWidth = 8;
[[UIColor redColor] setStroke];
// Add the outer circle
CGContextAddEllipseInRect(ctx, rect);
// Add the inner circle
CGContextAddEllipseInRect(ctx, CGRectInset(rect, innerWidth, innerWidth));
// Fill the path using the EO rule
CGContextEOFillPath(ctx);
}