小编Mat*_*ijs的帖子

在 iOS 上使用 CGContext 绘制渐变线

我正在寻找一种使用 CGContextRef 沿其路径绘制具有线性渐变的线的方法。我尝试了几种方法,但大多数都专注于用渐变填充区域(矩形),这不是我需要的。

我使用以下代码使用 CGPathRef 绘制实线。我实际上需要的是一个平滑的线性渐变,从线条的第一个点的 color1 开始,到线条的最后一个点的 color2 结束。

有谁知道如何实现这一目标?

- (CGMutablePathRef)generatedPath
{
    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, nil, 20, 10);
    CGPathAddLineToPoint(path, nil, 100, 100);
    CGPathAddLineToPoint(path, nil, 140, 120);
    CGPathAddLineToPoint(path, nil, 160, 100);
    CGPathAddLineToPoint(path, nil, 210, 70);
    CGPathAddLineToPoint(path, nil, 250, 10);

    return path;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGMutablePathRef path = [self generatedPath];
    CGContextAddPath(ctx, path);

    CGColorRef color = [UIColor redColor].CGColor;

    CGContextSetLineWidth(ctx, 8.0);

    CGContextSetStrokeColorWithColor(ctx, color);
    CGContextStrokePath(ctx);
}
Run Code Online (Sandbox Code Playgroud)

=========更新========================================== ========

我实际上发现这个问题也与我需要的非常相似:Gradient Polyline with …

gradient objective-c cgcontext polyline

5
推荐指数
0
解决办法
2865
查看次数

标签 统计

cgcontext ×1

gradient ×1

objective-c ×1

polyline ×1