2012-04-21 25 views
0

我試圖汲取其中用戶移動手指在iPad上的矩形:在iOS上,爲什麼在下面的代碼中沒有繪圖?

視圖控制器的接口:

@interface ViewController : UIViewController { 
    NSMutableArray *paths; 
} 

實現:

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    for (UITouch *touch in touches) { 
     CGPoint location = [touch locationInView:self.view]; 

     CGRect aRectangle = CGRectMake(location.x, location.y, 40, 40); 
     UIBezierPath *path = [UIBezierPath bezierPathWithRect:aRectangle]; 

     path = [UIBezierPath bezierPathWithOvalInRect:aRectangle]; 

     [paths addObject:path];  
    } 
} 

- (void)drawRect:(CGRect)rect { 
    for (UIBezierPath *path in paths) { 
     [path fill]; 
    } 
} 

但絕對不會在屏幕上繪製。 ..我想也許我沒有告訴視圖刷新自己,並呼籲drawRect,但我試圖去iPad的主屏幕,並重新進入應用程序,仍然沒有表現出來?

(我打算使用點數組,但由於CGPoint不是一個將保留的對象,所以它不能被添加到可變數組中,並且在本地作用域結束後它將消失。它可以是一組點嗎?)

+0

請嘗試以下帖子以供繪製......! http://stackoverflow.com/questions/10226130/draw-lines-a-touches-event-not-work-perfectly-on-fullscreen-mode-in-iphone 謝謝..! – Dinesh 2012-04-21 04:53:49

回答

3

drawRect是從UIView而不是UIViewController的方法。您需要創建自定義UIView子類並覆蓋其中的drawRect,然後將自定義視圖類綁定到XIB/NIB中的視圖(如果使用Interface Builder構建UI結構)。

參考iPhone: why isn't drawRect getting called?

+0

可變數組如何傳遞給UIView對象? – 2012-04-21 05:02:07

+0

您可以將'@property(retain)NSMutableArray * path'添加到您的自定義UIView子類,並通過'self.view.path'在'ViewController'類中對其進行訪問。 – Hailei 2012-04-21 05:03:57

+0

我沒有選擇'ViewController.xib'並選擇Custom Class爲TestView ...但在'ViewController.m'中,如果我執行'self.view.paths',它會說「Property'paths'not found on UIView類型的對象「 – 2012-04-21 05:15:44

1

首先,你應該實現在UIView,而不是UIViewController這些方法。


其次,不要自己調用drawRect!

我想也許如果你希望你的看法重繪一次抽取週期/幀,呼籲-setNeedsDisplay上我沒有告訴視圖更新自身,並呼籲 的drawRect

+0

的路徑添加後,我的意思是使Win32上的視圖無效,這樣'drawRect'將被調用 – 2012-04-21 05:17:54

+0

調用'-setNeedsDisplay',這將迫使它重繪。 – 2012-04-21 06:00:28

相關問題