我已经阅读了文档,但是我并不清楚如何使用CGPath绘制多边形。我所需要做的就是绘制一个类似于这样的CGPath:
__
\ \
\ \
\__\
请问有没有人能提供一个代码片段来完成这个问题?
此外,我假设CGPathContainsPoint可以帮助我确定一个点是否位于该路径内?或者该路径必须是一个实心的图形?
还有,我该如何移动CGPath?像在CGRect中更改原点一样简单吗?
谢谢。
-Oscar
我已经阅读了文档,但是我并不清楚如何使用CGPath绘制多边形。我所需要做的就是绘制一个类似于这样的CGPath:
__
\ \
\ \
\__\
请问有没有人能提供一个代码片段来完成这个问题?
此外,我假设CGPathContainsPoint可以帮助我确定一个点是否位于该路径内?或者该路径必须是一个实心的图形?
还有,我该如何移动CGPath?像在CGRect中更改原点一样简单吗?
谢谢。
-Oscar
这是使用CGPath创建三角形的示例,您只需要放置点即可。
var path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0) //start from here
CGPathAddLineToPoint(path, nil, 20, 44)
CGPathAddLineToPoint(path, nil, 40, 0)
CGPathAddLineToPoint(path, nil, 0, 0)
//and to use in SpriteKit, for example
var tri = SKShapeNode(path: path)
var color = NSColor.blueColor()
tri.strokeColor = color
tri.fillColor = color
这是结果
你应该像这样做:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);
for(int idx = 0; idx < self.points.count; idx++)
{
point = [self.points objectAtIndex:idx];//Edited
if(idx == 0)
{
// move to the first point
CGContextMoveToPoint(context, point.x, point.y);
}
else
{
CGContextAddLineToPoint(context, point.x, point.y);
}
}
CGContextStrokePath(context);
}
请注意,这里的points是你想画多边形的点数组。 因此,它应该是一个循环路径,例如:如果你正在绘制三个点的三角形 (x1, x2, x3)
,那么你应该传入数组 (x1, x2, x3, x1)
。
希望这能帮到你。
Draelach的回答已更新至Swift 4:
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 20, y: 44))
path.addLine(to: CGPoint(x: 40, y: 0))
path.addLine(to: CGPoint(x: 0, y: 0))
let tri = SKShapeNode(path: path)
斯坦福大学的iPhone CS193P课程有一个名为HelloPoly的项目,可能正是你想要的 - 参见课程主页以获取规格说明,然后观看视频了解它是如何实现的(并搜索那些完成了该任务的人们提供的解决方案)。