iOS – 如何沿路径绘制渐变

前端之家收集整理的这篇文章主要介绍了iOS – 如何沿路径绘制渐变前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我想要实现的效果

enter image description here

这就是我现在的效果

enter image description here

基本上,我需要沿弧的路径绘制渐变,而不是沿弧线线性绘制.我尝试了很多方法,其中一些产生了相同的结果,但其中一些产生了远远超出预期的结果.

这是我现在的代码

CGFloat lineSize = 12;
    CGFloat radius = self.frame.size.width/2 - lineSize;

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //Define gradient
    CGFloat colors [] =
    {
        0.9451f,0.5804f,0.2431f,1.0f,0.9922f,0.9490f,0.9020f,0.8706f,0.9412f,0.2941f,0.6863f,0.9176f,1.0f
    };

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace,colors,NULL,5);
    CGColorSpaceRelease(baseSpace),baseSpace = NULL;

    //Define arc angle and points
    CGFloat startAngle = 3.0f/4.0f * M_PI;
    CGFloat endAngle = 1.0f/4.0f * M_PI;

    CGFloat a = radius * cos(45);
    CGFloat o = a * tan(45);

    CGFloat y = CGRectGetMidY(rect) + o;

    CGPoint startPoint = CGPointMake(0,y);
    CGPoint endPoint = CGPointMake(self.frame.size.width,y);

    CGMutablePathRef arc = CGPathCreateMutable();
    CGPathAddArc(arc,CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startAngle,endAngle,NO);

    CGPathRef strokedArc = CGPathCreateCopyByStrokingPath(arc,10,kCGLineCapButt,kCGLineJoinMiter,10);

    CGContextAddPath(ctx,strokedArc);
    CGContextClip(ctx);

    CGContextDrawLinearGradient(ctx,gradient,startPoint,endPoint,0);
    CGGradientRelease(gradient);

我也试过改变这段代码

CGMutablePathRef arc = CGPathCreateMutable();
    CGPathAddArc(arc,0);
    CGGradientRelease(gradient);

这个区块代码

CGContextAddArc(ctx,NO);

CGContextSetLineWidth(ctx,lineSize);
CGContextSetLineCap(ctx,kCGLineCapRound);

CGContextReplacePathWithStrokedPath(ctx);
CGContextClip(ctx);

CGContextDrawLinearGradient(ctx,0);
CGGradientRelease(gradient),gradient = NULL;

但仍然产生与我现在拥有的结果类似的结果.

解决方法

尝试更改渐变值.

更改

//Define gradient
    CGFloat colors [] =
    {
        0.9451f,1.0f
    };

对某些对称的价值观.喜欢

CGFloat colors [] =
    {
        1.0f,0.7432f,1.0f
    };

猜你在找的iOS相关文章