2009-11-04 108 views
1

我正在嘗試通過觸摸它來在屏幕上繪製形狀的應用程序。繪製形狀時線條被擦除

我可以從一個點畫一條線到另一個點,但是它會在每個新的平局上消除。

這裏是我的代碼:

CGPoint location; 
CGContextRef context; 
CGPoint drawAtPoint; 
CGPoint lastPoint; 
-(void)awakeFromNib{ 
    //[self addSubview:noteView]; 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [[event allTouches] anyObject]; 
    location = [touch locationInView:touch.view]; 
    [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)]; 
} 

- (void)drawRect:(CGRect)rect { 
    context = UIGraphicsGetCurrentContext(); 
    [[UIColor blueColor] set]; 
    CGContextSetLineWidth(context,10); 
    drawAtPoint.x =location.x; 
    drawAtPoint.y =location.y; 
    CGContextAddEllipseInRect(context,CGRectMake(drawAtPoint.x, drawAtPoint.y, 2, 2)); 
    CGContextAddLineToPoint(context,lastPoint.x, lastPoint.y); 
    CGContextStrokePath(context); 

    lastPoint.x =location.x; 
    lastPoint.y =location.y; 
} 

感謝您的幫助 -

尼爾。

回答

2

正如您發現的,-drawRect是您顯示視圖內容的地方。你只能在屏幕上看到你在這裏畫的東西。

這比Flash更低級別,您可以在舞臺上添加一個包含線條的動畫片段,並且稍後添加另一個包含線條的動畫片段,現在您可以看到 - 兩行!

你需要做一些工作,prdobably設立類似..

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

    UITouch *touch = [[event allTouches] anyObject]; 
    location = [touch locationInView:touch.view]; 

    [self addNewLineFrom:lastPoint to:location]; 

    lastPoint = location; 

    [self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)]; 
} 

- (void)drawRect:(CGRect)rect { 

    context = UIGraphicsGetCurrentContext(); 

    for(Line *eachLine in lineArray) 
     [eachLine drawInContext:context]; 

} 

我想你可以看到如何充實這一出你所需要的。

解決此問題的另一種方法是使用CALayers。使用這種方法,您不會在內部繪製 - (void)drawRect - 您可以添加和移除圖層,在它們內部繪製您喜歡的圖像,視圖將根據需要處理合成它們並繪製到屏幕上。可能更多你在找什麼。

+0

我想你的意思是CALayers而不是UILayers。他仍然需要在CALayer的drawInContext:方法或委託-drawLayer:inContext:方法中進行一些自定義繪圖,但是您說得對,直到重繪後纔會保留其內容。 – 2009-11-04 13:41:22

+0

謝謝,你的權利 - 我已經讚賞了答案 – 2009-11-04 15:05:23

1

每調用一次drawRect,就從一張空白的石板開始。如果您沒有跟蹤您之前繪製的所有內容以便再次繪製,那麼最終只會繪製最新的手指刷卡,而不是任何舊手指。每次調用drawRect時,都必須跟蹤所有的手指滑動操作以重新繪製它們。

0

而不是重新繪製每一行,您可以繪製圖像,然後在您的drawRect:方法中顯示圖像。圖像會爲你積累線條。當然,這種方法使得撤銷更難實施。

iPhone Application Programming Guide

使用UIGraphicsBeginImageContext 函數來創建一個新的基於圖像的 圖形上下文。創建此 上下文後,您可以將圖像 的內容繪製到其中,然後使用 UIGraphicsGetImageFromCurrentImageContext 函數根據您繪製的 生成圖像。 (如果需要,您甚至可以繼續繪製並生成 附加圖像。)創建圖像時,請使用 UIGraphicsEndImageContext函數關閉圖形上下文。如果 更喜歡使用Core Graphics,則可以使用CGBitmapContextCreate函數 創建位圖圖形上下文 並將圖像內容繪製到其中。 當你完成繪圖時,使用 CGBitmapContextCreateImage函數 從位圖 上下文創建一個CGImageRef。您可以直接繪製Core 圖形圖像或使用它 初始化UIImage對象。