iOS:CGContextStrokePath 不断更新路径
我想构建一个小线图,当我调用 setPointInGraph:
方法时,该线图会得到更新。每次我调用它时,我都希望用我刚刚添加的点更新图表,因此从我的最后一个点画一条线。我在下面的代码中看到问题,在“drawRect:”中,它只是不断覆盖旧路径。
- (void)setPointInGraph:(float)p {
self.point = p;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat maxX = CGRectGetMaxX(rect);
CGFloat maxY = CGRectGetMaxY(rect);
CGColorRef strokeColor = [self.lineColor CGColor];
CGContextSetStrokeColorWithColor(context, strokeColor);
CGContextSetLineWidth(context, self.lineWidth);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0.0, maxY - maxY * self.point);
CGContextAddLineToPoint(context, maxX * (point / count), maxY - maxY * self.point);
CGContextStrokePath(context);
count++;
}
如何保留路径(例如属性)并在我选择时更新它?如何不断添加到此路径而不覆盖它?
I am wanting to build a small line graph that get updated when I call my setPointInGraph:
method. Each time I call that, I want the graph to be updated with the point that I just added, and therefore draw a line from my last point. I see the problem in my code below, in 'drawRect:' that it just keeps overwriting the old path.
- (void)setPointInGraph:(float)p {
self.point = p;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat maxX = CGRectGetMaxX(rect);
CGFloat maxY = CGRectGetMaxY(rect);
CGColorRef strokeColor = [self.lineColor CGColor];
CGContextSetStrokeColorWithColor(context, strokeColor);
CGContextSetLineWidth(context, self.lineWidth);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0.0, maxY - maxY * self.point);
CGContextAddLineToPoint(context, maxX * (point / count), maxY - maxY * self.point);
CGContextStrokePath(context);
count++;
}
How can I keep the path around (such as a property) and update it when I choose to? How can I continually add to this path not overwrite it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用UIBezierPath。您可以通过调用
addLineToPoint
来添加新线段。Use
UIBezierPath
. You can add new segments by callingaddLineToPoint
.不要在图形上下文中创建路径,而是创建一个常规路径,然后对其进行描边:
当您需要更新路径时,创建前一个路径的可变副本,并向其中添加线条:
然后再次绘制它:
Instead of creating a path in the graphics context, create a regular path which you then stroke:
When you need to update the path, create a mutable copy of the previous path, and add the line to it:
And then draw it again: