27

我知道如何画一条简单的线:

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

我知道如何做一个渐变矩形,ig:

CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB();
size_t num_locations = 2;
CGFloat locations[2] = { 1.0, 0.0 };
CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0,    1.0, 1.0, 1.0, 1.0 };

CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations);

CGPoint myStartPoint, myEndPoint;
myStartPoint.x = 0.0;
myStartPoint.y = 0.0;
myEndPoint.x = 0.0;
myEndPoint.y = 10.0;
CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0);

但是我怎么能画一条带有渐变的线,从黑色淡入到白色(也可能在另一边淡出到黑色)?

4

7 回答 7

35

可以使用渐变或任何其他填充效果(例如图案)来描边任意路径。

如您所见,描边路径不会使用当前渐变进行渲染。只有填充的路径使用渐变(当您将它们变成剪辑然后绘制渐变时)。

但是,Core Graphics 有一个非常酷的程序CGContextReplacePathWithStrokedPath,可以将您打算描边的路径转换为填充时等效的路径。

在幕后,CGContextReplacePathWithStrokedPath围绕您的笔划路径构建一个边缘多边形,并将其切换为您定义的路径。我推测 Core Graphics 渲染引擎可能调用CGContextStrokePath.

这是Apple关于此的文档:

Quartz 使用当前图形上下文的参数创建一个描边路径。创建新路径,以便填充它绘制与抚摸原始路径相同的像素。您可以像使用任何上下文的路径一样使用此路径。例如,您可以通过调用此函数然后调用函数 CGContextClip 来剪辑到路径的描边版本。

因此,将路径转换为可以填充的内容,将其转换为剪辑,然后绘制渐变。效果就好像你已经用渐变描边了路径。

代码

它看起来像这样……</p>

    // 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
    );

补充说明

值得强调的是上面的部分文档:

Quartz使用当前图形上下文的参数创建一个描边路径。

明显的参数是线宽。但是,使用了所有的线条绘制状态,例如笔划图案、斜接限制、线条连接、大写、虚线图案等。这使得该方法非常强大。

有关其他详细信息,请参阅此 SO question答案

于 2014-07-30T10:47:21.633 回答
20

经过几次尝试,我现在确定渐变不会影响笔画,所以我认为用 . 绘制渐变线是不可能的CGContextStrokePath()。对于水平线和垂直线,解决方案是CGContextAddRect()改用,幸运的是,这正是我所需要的。我换了

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

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

一切正常。感谢 Brad Larson 的关键提示。

于 2009-08-20T16:42:52.920 回答
8

您可以使用核心动画层。您可以通过设置其路径属性为您的线条使用CAShaperLayer,然后您可以使用CAGradientLayer作为您的形状图层的图层蒙版,这将导致线条褪色。

将您的 CGContext... 调用替换为对 CGPath... 的调用以创建线路路径。使用该路径在图层上设置路径字段。然后在渐变层中,指定要使用的颜色(可能是黑到白),然后将蒙版设置为线条层,如下所示:

 [gradientLayer setMask:lineLayer];

渐变层最酷的地方在于它允许您指定渐变将停止的位置列表,以便您可以淡入和淡出。它只支持线性渐变,但听起来可能适合您的需求。

如果您需要澄清,请告诉我。

编辑:现在我想到了,只需创建一个 CAGradientLayer,它就是您想要的线条的宽度/高度。指定渐变颜色(黑色到白色或黑色到清晰的颜色)以及 startPoint 和 endtPoints,它应该可以满足您的需求。

于 2009-08-20T04:28:01.843 回答
8

画完线后,你可以打电话

CGContextClip(context);

将进一步的绘图剪辑到您的线条区域。如果您绘制渐变,它现在应该包含在线条区域内。请注意,如果您只想显示渐变,而不是下方的线条,则需要为线条使用清晰的颜色。

有可能线条太细而无法显示渐变,在这种情况下,您可以使用CGContextAddRect()定义较厚的区域。

我在此处的回答中提供了一个使用此上下文剪辑的更详细示例。

于 2009-08-20T12:50:31.683 回答
1

我创建了 Benjohn 答案的 Swift 版本。

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)
    }
}

如果 createPath() 方法创建了一个三角形,你会得到这样的结果:

在此处输入图像描述

希望这对任何人都有帮助!

于 2020-08-10T08:00:26.773 回答
0
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);

它为我工作。

于 2012-05-30T06:55:31.130 回答
0

斯威夫特 5版本

这段代码对我有用。

override func draw(_ rect: CGRect) {
    super.draw(rect)
    
    guard let context = UIGraphicsGetCurrentContext() else {
        return
    }
    
    drawGradientBorder(rect, context: context)
}

fileprivate 
func drawGradientBorder(_ rect: CGRect, context: CGContext) {
    context.saveGState()
    let path = ribbonPath()
    context.setLineWidth(5.0)
    context.addPath(path.cgPath)
    context.replacePathWithStrokedPath()
    context.clip()
    
    let baseSpace = CGColorSpaceCreateDeviceRGB()
    let gradient = CGGradient(colorsSpace: baseSpace, colors: [start.cgColor, end.cgColor] as CFArray, locations: [0.0 ,1.0])!
    context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: rect.height/2), end: CGPoint(x: rect.width, y: rect.height/2), options: [])
    context.restoreGState()
}

fileprivate 
func ribbonPath() -> UIBezierPath {
    let path = UIBezierPath()
    path.move(to: CGPoint.zero)
    path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth, y: 0))
    path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth - ribbonGap, y: bounds.maxY))
    path.addLine(to: CGPoint(x: 0, y: bounds.maxY))
    path.close()
    return path
}
于 2021-03-29T20:46:30.273 回答