UIBezierPath with color gradient

前端 未结 5 1668
孤街浪徒
孤街浪徒 2021-02-08 15:21

I\'ve got an question about UIBezierPath.

For example I\'ve got this path:

\"\"

Now I want to have

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 15:46

    You will archive it by using QuartsCore. If you want get image with your figure, you can call UIGraphicsBeginImageContext(), if you want draw it on UIView you should overload method - (void)drawRect:(CGRect)rect of UIView. You can add path to context, and use it for clipping context (Don't forget save the context state before). After you can draw the gradient. The gradient will be clipped by path.

    You will get something like this:

    CGPathRef path = [bezierPath CGPath];
    CGContextSaveGState(context);
    
    CGContextAddPath(context, path);
    CGContextClip(context);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    NSArray *colors = [NSArray arrayWithObjects:(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, nil];
    CGGradientRef gradient = CGGradientCreateWithColors( colorSpace, (CFArrayRef)colors, NULL);
    CGColorSpaceRelease(colorSpace);
    colorSpace = NULL;
    
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0.0, 0.0), CGPointMake(100.0, 100.0), kNilOptions);
    
    CGContextRestoreGState(context);
    

提交回复
热议问题