2012-04-06 51 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失效。