How to draw a gradient line (fading in/out) with Core Graphics/iPhone?

后端 未结 6 575
轻奢々
轻奢々 2020-12-04 15:02

I know how to draw a simple line:

CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(conte         


        
6条回答
  •  -上瘾入骨i
    2020-12-04 15:14

    After several tries I'm now sure that gradients doesn't affect strokes, so I think it's impossible to draw gradient lines with CGContextStrokePath(). For horizontal and vertical lines the solution is to use CGContextAddRect() instead, which fortunately is what I need. I replaced

    CGContextMoveToPoint(context, x, y);
    CGContextAddLineToPoint(context, x2, y2);
    CGContextStrokePath(context);
    

    with

    CGContextSaveGState(context);
    CGContextAddRect(context, CGRectMake(x, y, width, height));
    CGContextClip(context);
    CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);
    

    and everything works fine. Thanks to Brad Larson for the crucial hint.

提交回复
热议问题