2012-04-06 54 views
0

这个任务是,在运行时在自定义地图上绘制路径,这些地图在滚动视图中使用,然后每当位置坐标(lat,long)更新时,我都必须在运行时绘制路径。这个问题在这里试图解决的是,我已经做了一个类'图形'这是UIView的子类,其中我编写了'drawrect:'方法的图形。所以当我将图形作为滚动视图的子视图添加到图像上时,线条会绘制,但我需要继续绘制线条,就像它是路径一样。我需要在运行时绘制线条,需要不断更新'CGContextStrokeLineSegments'方法的点(x,y)。代码:核心图形,如何在运行时画线?

的ViewController:

- (void)loadView { 
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone]; 
CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame]; 
scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect]; 
graph = [[graphics alloc] initWithFrame:fullScreenRect]; 
scrollView.contentSize=CGSizeMake(320,480); 

UIImageView *tempImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fortuneCenter.png"]]; 

self.view=scrollView; 
[scrollView addSubview:tempImageView2]; 
scrollView.userInteractionEnabled = YES; 
scrollView.bounces = NO; 
[scrollView addSubview:graph]; 
} 

Graphics.m:

- (id)initWithFrame:(CGRect)frame 
{ 
self = [super initWithFrame:frame]; 
if (self) { 
    // Initialization code 
    self.backgroundColor = [UIColor clearColor]; 
} 
return self; 
} 

- (void)drawRect:(CGRect)rect 
{ 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGPoint point [2] = { CGPointMake(160, 100), CGPointMake(160,300)}; 
CGContextSetRGBStrokeColor(context, 255, 0, 255, 1); 
CGContextStrokeLineSegments(context, point, 2); 
} 

因此,如何能在我运行时绘制线条。我现在只是模拟,所以即时通讯不使用实时数据(坐标)。只需要使用虚拟数据(x,y的坐标)进行模拟。让我们说有一个按钮,每当我按下它更新坐标,所以路径延伸。

回答

1

最简单的方法是将表示点的实例变量添加到UIView子类中。 然后,每当路径改变时,适当更新伊娃,并在定制UIView(或甚至在其超级检视中)呼叫-setNeedsDisplaysetNeedsDisplayInRect。运行时将重新绘制新的路径。

1

你只需要动态调整CGPoint point[]的大小就可以了。

您可以使用mallocstd::vector或甚至NSMutableData来存储您添加的点。然后你将该数组传递给CGContextStrokeLineSegments

如果你需要2点,将CGPoint point[2]移动到ivar,这样你可以存储位置,然后(如Rich指出的)在这些值(或数组)被改变时适当地使rects失效。