CGPath带有轮廓线。

9
我正在尝试绘制一个具有描边的CGPath。
基本上,我想要使用CGPath画一条线。然后我想回去在最后一个CGPath的两侧画线,使其呈现轮廓效果。
这条线可以弯曲和转向,但我始终需要外部的两条线跟随它。
编辑:我需要能够使线的中间透明,但轮廓为纯黑色。

请参考以下网址:https://dev59.com/qG035IYBdhLWcg3wZ_Qt - Dixit Patel
2个回答

15

使用CGPathCreateCopyByStrokingPath函数以指定的宽度描边旧路径并创建一个新路径。然后使用kCGPathFillStroke绘制新路径。

- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();

  CGMutablePathRef path = CGPathCreateMutable();
  CGPathMoveToPoint(path, NULL, 50, 50);
  CGPathAddLineToPoint(path, NULL, 200, 200);

  CGPathRef thickPath = CGPathCreateCopyByStrokingPath(path, NULL, 10, kCGLineCapButt, kCGLineJoinBevel, 0);
  CGContextAddPath(context, thickPath);

  CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
  CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
  CGContextSetLineWidth(context, 3);
  CGContextDrawPath(context, kCGPathFillStroke);

  CGPathRelease(thickPath);
  CGPathRelease(path);
}

我该如何绘制两个不同的CGPath并为每个路径分配不同的颜色? - Van Du Tran

5
最简单的解决方案就是对路径进行两次描边。首先使用较大的黑色描边宽度描边路径,然后再使用略小的蓝色描边宽度描边相同的路径。
编辑:如果我没记错的话,您可以使用CGPathCreateCopyByStrokingPath(...)创建一个新路径,然后可以同时描边和填充。然后您可以使用半透明颜色。
从文档中可以看到:

CGPathCreateCopyByStrokingPath

Creates a stroked copy of another path.

CGPathRef CGPathCreateCopyByStrokingPath(
                                         CGPathRef path,
                                         const CGAffineTransform *transform,
                                         CGFloat lineWidth,
                                         CGLineCap lineCap,
                                         CGLineJoin lineJoin,
                                         CGFloat miterLimit 
                                         ); 

Parameters
path
The path to copy.

transform
A pointer to an affine transformation matrix, or NULL if no transformation is needed. If specified, Quartz applies the transformation to elements of the converted path before adding them to the new path.

lineWidth
The line width to use, in user space units. The value must be greater than 0.

lineCap
A line cap style constant—kCGLineCapButt (the default), kCGLineCapRound, or kCGLineCapSquare. See “CGLineCap”.

lineJoin
A line join value—kCGLineJoinMiter (the default), kCGLineJoinRound, or kCGLineJoinBevel. See “CGLineJoin”.

miterLimit
The miter limit to use.


1
我想让中间的颜色半透明。加一个黑色的大线条在它后面会使这个目标无法实现。 - endy
我现在明白你的意思了,感谢你的帮助。 - endy
@David,这个 API 的 Swift 3 的替代方案是什么? - Vivek Sehrawat
@VivekSehrawat 快速在线搜索显示它是 copy(strokingWithWidth:lineCap:lineJoin:miterLimit:transform:) - David Rönnqvist
@DavidRönnqvist - 谢谢,我明白了。 - Vivek Sehrawat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接