2009-11-04 59 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对象。