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

后端 未结 6 555
轻奢々
轻奢々 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条回答
  • 2020-12-04 15:09

    It is possible to stroke arbitrary paths with a gradient, or any other fill effect, such as a pattern.

    As you have found, stroked paths are not rendered with the current gradient. Only filled paths use the gradient (when you turn them in to a clip and then draw the gradient).

    However, Core Graphics has an amazingly cool procedure CGContextReplacePathWithStrokedPath that will transform the path you intend to stroke in to a path that is equivalent when filled.

    Behind the scenes, CGContextReplacePathWithStrokedPath builds up an edge polygon around your stroke path and switches that for the path you have defined. I'd speculate that the Core Graphics rendering engine probably does this anyway in calls to CGContextStrokePath.

    Here's Apple's documentation on this:

    Quartz creates a stroked path using the parameters of the current graphics context. The new path is created so that filling it draws the same pixels as stroking the original path. You can use this path in the same way you use the path of any context. For example, you can clip to the stroked version of a path by calling this function followed by a call to the function CGContextClip.

    So, convert your path in to something you can fill, turn that in to a clip, and then draw your gradient. The effect will be as if you had stroked the path with the gradient.

    Code

    It'll look something like this…

        // Get the current graphics context.
        //
        const CGContextRef context = UIGraphicsGetCurrentContext();
    
        // Define your stroked path. 
        //
        // You can set up **anything** you like here.
        //
        CGContextAddRect(context, yourRectToStrokeWithAGradient);
    
        // Set up any stroking parameters like line.
        //
        // I'm setting width. You could also set up a dashed stroke
        // pattern, or whatever you like.
        //
        CGContextSetLineWidth(context, 1);
    
        // Use the magical call.
        //
        // It turns your _stroked_ path in to a **fillable** one.
        //
        CGContextReplacePathWithStrokedPath(context);
    
        // Use the current _fillable_ path in to define a clipping region.
        //
        CGContextClip(context);
    
        // Draw the gradient.
        //
        // The gradient will be clipped to your original path.
        // You could use other fill effects like patterns here.
        //
        CGContextDrawLinearGradient(
          context, 
          yourGradient, 
          gradientTop, 
          gradientBottom, 
          0
        );
    

    Further notes

    It's worth emphasising part of the documentation above:

    Quartz creates a stroked path using the parameters of the current graphics context.

    The obvious parameter is the line width. However, all line drawing state is used, such as stroke pattern, mitre limit, line joins, caps, dash patterns, etc. This makes the approach extremely powerful.

    For additional details see this answer of this S.O. question.

    0 讨论(0)
  • 2020-12-04 15:09
    CGContextMoveToPoint(context, frame.size.width-200, frame.origin.y+10);
    CGContextAddLineToPoint(context, frame.size.width-200, 100-10);
    CGFloat colors[16] = { 0,0, 0, 0,
        0, 0, 0, .8,
        0, 0, 0, .8,
        0, 0,0 ,0 };
    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 4);
    
    CGContextSaveGState(context);
    CGContextAddRect(context, CGRectMake(frame.size.width-200,10, 1, 80));
    CGContextClip(context);
    CGContextDrawLinearGradient (context, gradient, CGPointMake(frame.size.width-200, 10), CGPointMake(frame.size.width-200,80), 0);
    CGContextRestoreGState(context);
    

    its work for me.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 15:15

    I created a Swift version of Benjohn's answer.

    class MyView: UIView {
        override func draw(_ rect: CGRect) {
        super.draw(rect)
    
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
    
        context.addPath(createPath().cgPath)
        context.setLineWidth(15)
        context.replacePathWithStrokedPath()
        context.clip()
    
        let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor] as CFArray, locations: [0, 0.4, 1.0])!
        let radius:CGFloat = 200
        let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
        context.drawRadialGradient(gradient, startCenter: center, startRadius: 10, endCenter: center, endRadius: radius, options: .drawsBeforeStartLocation)
        }
    }
    

    If the createPath() method creates a triangle, you get something like this:

    Hope this helps anyone!

    0 讨论(0)
  • 2020-12-04 15:24

    You can use Core Animation layers. You can use a CAShaperLayer for your line by settings its path property and then you can use a CAGradientLayer as a layer mask to your shape layer that will cause the line to fade.

    Replace your CGContext... calls with calls to CGPath... calls to create the line path. Set the path field on the layer using that path. Then in your gradient layer, specify the colors you want to use (probably black to white) and then set the mask to be the line layer like this:

     [gradientLayer setMask:lineLayer];
    

    What's cool about the gradient layer is that is allows you to specify a list of locations where the gradient will stop, so you can fade in and fade out. It only supports linear gradients, but it sounds like that may fit your needs.

    Let me know if you need clarification.

    EDIT: Now that I think of it, just create a single CAGradientLayer that is the width/height of the line you desire. Specify the gradient colors (black to white or black to clear color) and the startPoint and endtPoints and it should give you what you need.

    0 讨论(0)
  • 2020-12-04 15:25

    After you draw the line, you can call

    CGContextClip(context);
    

    to clip further drawing to your line area. If you draw the gradient, it should now be contained within the line area. Note that you will need to use a clear color for your line if you just want the gradient to show, and not the line underneath it.

    There is the possibility that a line will be too thin for your gradient to show up, in which case you can use CGContextAddRect() to define a thicker area.

    I present a more elaborate example of using this context clipping in my answer here.

    0 讨论(0)
提交回复
热议问题