问题描述
|
我的应用程序中有一个基本的地图视图,其中包含一组用户可定义的航路点。加载视图后,我会绘制一条连接航路点的路径。这很好。
但是,当用户在视图周围拖动航路点时,我希望它重新绘制路径,这就是我的问题。我不知道如何在第一次之后就画出任何东西。这是我的代码:
- (void)drawRect:(CGRect)rect { ////// works perfectly
context = UIGraphicsGetCurrentContext();
CGContextSetRGBstrokeColor(context,1,.7);
CGContextSetlinewidth(context,20.0);
WaypointViewController *w = [arrayOfWaypoints objectAtIndex:0];
CGPoint startPoint = w.view.center;
CGContextMovetoPoint(context,startPoint.x,startPoint.y);
for (int i = 1; i<[arrayOfWaypoints count]; i++) {
WaypointViewController *w2 = [arrayOfWaypoints objectAtIndex:i];
CGPoint nextPoint = w2.view.center;
CGContextAddLinetoPoint(context,nextPoint.x,nextPoint.y);
}
CGContextstrokePath(context);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (moving) {
UITouch *touch = [touches anyObject];
currentWaypoint.view.center = [touch locationInView:self];
[delegate setUserInteraction:NO];
[self drawInContext:context];
[NSThread detachNewThreadSelector:@selector(drawInContext:) toTarget:self withObject:nil];
}
}
- (void)drawInContext:(CGContextRef)context { ///gets called,but does nothing
CGContextSetRGBstrokeColor(context,nextPoint.y);
}
CGContextstrokePath(context);
}
解决方法
您不能在其他任何地方使用ѭ1中激活的上下文。
而不是呼叫
[self drawInContext:context]
呼叫[self setNeedsDisplay]
您不知道ѭ1中指向的上下文是否已释放或仍处于活动状态,但是无论哪种方式,都无法将放入该上下文中的位显示在屏幕上。
另外,请在此处阅读有关在iOS上绘图的文档
,drawRect:
返回后,您可能无法保存上下文以供使用。您需要做的是调用[self setNeedsDisplay]
(或setNeedsDisplayInRect:
,如果可以确定更改的边界矩形),这将导致系统再次为您调用drawRect:
。
,您只能在drawRect中进行所有绘图...希望这会有所帮助...因此-(void)drawInContext:(CGContextRef)context将无法进行任何绘图。如果在用户进行触摸操作之后,您需要进行一些重绘,则需要在触摸方法中调用[self setNeedsDisplay]。