在iPhone上绘制空心圆

12
我需要绘制以下图片enter image description here

灰色部分是我想在另一张图像上绘制的内容。我需要使用CGContext方法的哪些代码?我尝试使用CGContextAddArc,但失败了,因为当我填充描边时,中心空洞也被灰色纹理填充了。
非常感谢任何帮助。
信息: 我已经拥有完整的蓝色图像,我需要在蓝色图像上方添加半圆形。
谢谢

当您尝试使用CGContext创建一个甜甜圈形状并将其添加到图层或形状图层中时,您会如何解决问题?很抱歉,我现在还无法理解这个问题,所以目前只是在空射。 - tosi
3个回答

25

请查看Core Graphics文档中的填充路径部分。基本上,您需要将两个弧形添加到路径中(外部和内部),然后利用Core Graphics的填充规则来实现目标效果。代码可能如下所示:

CGMutablePathRef path = CGPathCreateMutable();

// Add the outer arc to the path (as if you wanted to fill the entire circle)
CGPathMoveToPoint(path, ...);
CGPathAddArc(path, ...);
CGPathCloseSubpath(path);

// Add the inner arc to the path (later used to substract the inner area)
CGPathMoveToPoint(path, ...);
CGPathAddArc(path, ...);
CGPathCloseSubpath(path);

// Add the path to the context
CGContextAddPath(context, path);

// Fill the path using the even-odd fill rule
CGContextEOFillPath(context);

CGPathRelease(path);

10

在进一步研究Ole Begemann的答案并进行了一些修改后,我成功地实现了要求。

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_grey_pattern.png"]].CGColor);
CGMutablePathRef path = CGPathCreateMutable();
CGContextSetLineWidth(context, 40);
CGPathAddArc(path, NULL, aRect.size.width/2, aRect.size.height/2, 45, 0*3.142/180, angle*3.142/180, 0);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);

所以我只使用了一条弧线,然后用更高的宽度描边。


4

我这里提供一段Swift绘制甜甜圈(或空心圆)的代码,虽然有些不相关但算是相关吧。

class func drawDonut(donutColor: UIColor, rect: CGRect, innerDonutProportion: CGFloat) {

    //// Variable Declarations
    let innerDonutSide: CGFloat = rect.size.width * innerDonutProportion
    let innerDonutOffset: CGFloat = 0.5 * (rect.size.width - innerDonutSide)
    let innerDonutRect = CGRectMake(innerDonutOffset, innerDonutOffset, innerDonutSide, innerDonutSide)

    //// InnerCircle Drawing
    let innerCirclePath = UIBezierPath(ovalInRect: innerDonutRect)

    //// Outer Circle Drawing
    let outerCirclePath = UIBezierPath(ovalInRect: rect)

    // Clip out the innerCirclePath
    outerCirclePath.appendPath(innerCirclePath)
    outerCirclePath.addClip()
    outerCirclePath.usesEvenOddFillRule = true;

    // and Fill the outerCircle
    donutColor.setFill()
    outerCirclePath.fill()
}

不错!但是对于rect.origin不是(0,0)的一般情况,您应该改用:let innerDonutRect = CGRectMake(rect.origin.x + innerDonutOffset,rect.origin.y + innerDonutOffset,innerDonutSide,innerDonutSide)。除此之外,您的代码完美地运行了。 - rene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接