如何用Core Graphics / iPhone绘制渐变弧线?
我知道如何绘制弧线
我也发现如何从这里画出一条渐变线
我发现两个函数可以绘制渐变:CGContextDrawLinearGradient和CGContextDrawRadialGradient.but我怎样才能绘制一个渐变圆弧? 我想要实现这样的画面:
我花了很长的时间寻找如何做到这一点,所以我认为我会这样做。 原来这两个答案都是对这个问题的出色答案:
从圆圈或圆环画出细分
为了我的目的,我只使用了该答案的绘图和渐变部分。 结构看起来或多或less像这样…
CGContextRef context = UIGraphicsGetCurrentcontext(); CGFloat arcStartAngle = M_PI; CGFloat arcEndAngle = 2 * M_PI; CGPoint startPoint = CGPointMake(...); CGPoint endPoint = CGPointMake(...); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGFloat colors[] = { 1.0, 0.0, 0.0, 1.0, //RGBA values (so red to green in this case) 0.0, 1.0, 0.0, 1.0 }; CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2); //Where the 2 is for the number of color components. You can have more colors throughout //your gradient by adding to the colors[] array, and changing the components value. CGColorSpaceRelease(colorSpace); //Now for the arc part... CGMutablePathRef arc = CGPathCreateMutable(); CGPathMoveToPoint(arc, NULL, startPoint.x, startPoint.y); //Here, the CGPoint self.arcCenter is the point around which the arc is placed, so maybe the //middle of your view. self.radius is the distance between this center point and the arc. CGPathAddArc(arc, NULL, self.arcCenter.x, self.arcCenter.y, self.radius, arcStartAngle, arcEndAngle, YES); //This essentially draws along the path in an arc shape CGPathRef strokedArc = CGPathCreateCopyByStrokingPath(arc, NULL, 5.0f, kCGLineCapButt, kCGLineJoinMiter, 10); CGContextSaveGState(context); CGContextAddPath(context, strokedArc); CGContextClip(context); CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); CGContextDrawPath(context, kCGPathFillStroke); CGGradientRelease(gradient); CGContextRestoreGState(context); //This all draws a gradient that is much larger than the arc itself, but using //CGContextClip, it clips out everything EXCEPT the colors in the arc. Saving and Restoring //the state allows you to preserve any other drawing going on. If you didn't use these, //then all other drawing would also be clipped.
我希望这有帮助。 如果有任何不清楚的地方,我build议你查看上面的问题链接。 这个问题的答案包含了我在这个答案中使用的一切,以及一些更加有用的绘图技巧。
你可以通过使用CGContextDrawRadialGradient()
来应用剪切path。 你可以做这样的事情:
CGContextBeginPath(context); CGContextMoveToPoint(context, startX, startY); CGContextAddArcToPoint(context, x1, y1, x2, y2, arcRadius); CGConextClosePath(context); CGContextClip(context); CGContextDrawRadialGradient(context, gradient, startCenter, startRadius, endCenter, endRadius, options);