gpt4 book ai didi

ios - Core Graphics/iPhone如何绘制渐变弧线?

转载 作者:技术小花猫 更新时间:2023-10-29 10:10:18 25 4
gpt4 key购买 nike

我会画圆弧

我还找到了如何从 here 中绘制渐变线

我发现有两个函数可以绘制渐变:CGContextDrawLinearGradient 和 CGContextDrawRadialGradient。但是如何绘制渐变弧线呢?我想像这张图那样实现: enter image description here

最佳答案

我也花了很长时间寻找如何做到这一点,所以我想我会发布我最终的做法。事实证明,这两个答案都是对这个问题的极好答案:

Draw segments from a circle or donut

出于我的目的,我只使用了该答案的绘图和渐变部分。结构看起来或多或少是这样的……

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.

希望对您有所帮助。如果有任何不清楚的地方,我建议您查看上面的问题链接。该问题的答案包含我在此答案中使用的所有内容以及一些更酷、更实用的绘画技巧。

关于ios - Core Graphics/iPhone如何绘制渐变弧线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com