2011-11-08 39 views
1

我正在爲一個班級進行作業,需要一點指導。我正在使用一個應用程序,將觸摸事件以及隨後的手指拖動到屏幕上的繪圖中。我需要弄清楚如何將每張圖紙保存在一個數組中,並將其全部刪除以響應搖動事件。iPhone - 根據觸摸事件在屏幕上繪圖

這是非常基本的 - 有一個HomeViewController(UIViewController)和一個佔用窗口的DoodleView(UIView)。 HomeViewController具有doodleview屬性,並在viewDidLoad方法中創建一個實例,將其指定給self.doodleview,然後調用addSubview。 touchesBegan,touchesMoved和touchesEnded方法屬於doodleview類。現在,每次點擊和拖動都會刪除前一個。

我最初試圖保存它們,是爲了創建HomeViewController的NSMutableArray「doodleViews」屬性,認爲每個touchesBegan事件都創建了doodleView的一個新實例,並且只是在該數組的最後一個元素上調用addSubview。這不起作用,我不知道爲什麼。任何提示都表示讚賞。

這裏是HomeViewController一個片段:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    CGRect window = [[UIScreen mainScreen] bounds]; 
    self.doodleView = [[DoodleView alloc] initWithFrame:window]; 

    CircleGestureRecognizer *recognizer = [[CircleGestureRecognizer alloc] initWithTarget:self action:@selector(handleCircleRecognizer:)]; 
    [self.doodleView addGestureRecognizer:recognizer]; 

    [self.view addSubview:self.doodleView]; 

} 

這裏是DoodleView一個片段:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event 
{ 
    NSLog(@"touches began"); 

    path = [UIBezierPath bezierPath]; 
    path.lineWidth = 15.0f; 
    path.lineCapStyle = kCGLineCapRound; 
    path.lineJoinStyle = kCGLineJoinRound; 

    UITouch *touch = [touches anyObject]; 
    [path moveToPoint:[touch locationInView:self]]; 
} 

- (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event 
{ 
    UITouch *touch = [touches anyObject]; 
    [path addLineToPoint:[touch locationInView:self]]; 
    [self setNeedsDisplay]; 
} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    [path addLineToPoint:[touch locationInView:self]]; 
    [self setNeedsDisplay]; 
} 

回答

0

你可能會想保存UIBezierPath *pathNSMutableArraytouchesEnded方法。然後在您的繪圖代碼中遍歷數組並繪製每條路徑。

當這個陣列中只有​​搖晃。

+0

我試過了,我得到0元素,當我這樣做:[self.drawings addObject:path]; NSLog(@「%d」,self.drawings.count);此外,繪圖是實時發生的,所以隨着手指的移動,drawRect被調用並且[path stroke]與其一起被調用。 – David

+0

@David;我沒有這種類型的項目在我面前看,但是。你有沒有嘗試過[self.drawing addObject:[path copy]]? – NJones