核心图形绘制线与轮廓

时间:2012-01-22 09:50:03

标签: iphone cocoa-touch core-graphics

我正在使用Core Graphics绘制一条宽度为4像素的任意一行,现在我希望这条线具有另一种颜色的1像素轮廓。我看不到任何可以实现这种“开箱即用”的CG功能,但我正在寻找有关如何完成的建议。这是我现有的代码:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);

CGPoint curPoint = [(NSValue*)[points objectAtIndex:0] CGPointValue];
CGContextMoveToPoint(context, curPoint.x, curPoint.y);

for( int i = 1; i < [points count]; i++ ) {
    curPoint = [(NSValue*)[points objectAtIndex:i] CGPointValue];
    CGContextAddLineToPoint(context, curPoint.x, curPoint.y);
    CGContextStrokePath(context);
    CGContextMoveToPoint(context, curPoint.x, curPoint.y);
}

这会产生单行。我想制作一条4px线,1px线突出显示4px线,如下所示:

http://img692.imageshack.us/img692/6196/lineexample.png

5 个答案:

答案 0 :(得分:5)

iOS 5.0添加了一项新功能CGPathCreateCopyByStrokingPath(),可以满足您的需求。

首先为黑色路径创建一个CGPathRef,然后使用CGPathCreateCopyByStrokingPath()创建一个副本。

这将为您提供一条新路径,您可以用黑色和笔划填充红色,以获得您想要的效果。

此外,创建路径有点慢。执行屏幕绘制时应避免创建路径。您的所有路径都应存储在RAM中,并准备好在开始绘制到屏幕之前drawRect:应该只绘制路径,而不是创建路径。

答案 1 :(得分:1)

与Abhi Beckert建议的相似,但您可以使用此功能:

CGContextReplacePathWithStrokedPath(CGContextRef c);

旧版SDK中也存在这种情况 - 例如iOS 4.1,MacOS X 10.6。
另外最好创建整个路径,然后在结尾处描边(或者同时描边和填充) - 换句话说,不需要在循环中使用 CGContextStrokePath

答案 2 :(得分:0)

我担心您必须再次绘制路径,并将线宽设置为1.如果您希望它位于4像素路径的外部,则必须相应地调整路径。

编辑:我想到了另一个选项 - 你可以描绘一个模式 - 请参阅Apple的QuartzDemo以获取示例。

答案 3 :(得分:0)

要为我自己的问题添加答案,可以通过在高亮颜色中绘制一条宽几个像素的线条,然后在顶部绘制实际线条来完成。这会产生轮廓效果。

答案 4 :(得分:-1)

没有内置方法将笔划转换为路径,然后描边该路径。也就是说,您可以通过绘制两次线来近似:一次使用6像素笔划(每边4像素+ 1),然后再使用不同颜色的4像素笔划

类似于:

CGContextRef context = UIGraphicsGetCurrentContext();

CGPoint curPoint = [(NSValue*)[points objectAtIndex:0] CGPointValue];
CGContextMoveToPoint(context, curPoint.x, curPoint.y);

for( int i = 1; i < [points count]; i++ ) {
    curPoint = [(NSValue*)[points objectAtIndex:i] CGPointValue];
    CGContextAddLineToPoint(context, curPoint.x, curPoint.y);
}

// Set your 1 pixel highlight color here using CGContextSetRGBStrokeColor or equivalent
// CGContextSetRGBStrokeColor(...)
CGContextSetLineWidth(context, 6.0);
CGContextStrokePath(context);


// Set your 4 pixel stroke color here using CGContextSetRGBStrokeColor or equivalent
// CGContextSetRGBStrokeColor(...)
CGContextSetLineWidth(context, 4.0);
CGContextStrokePath(context);

另一个想法是在绘制笔划之前通过CGContextSetShadowWithColor(context,CGSizeZero,1.0,yourHighlightColorHere)设置阴影,尽管这不会绘制具有完全不透明度的高光颜色。 (我也记不起影子属性的阴影笔画 - 我只用填充物来表示它们)