绘制形状时线条被擦除
我正在尝试制作一个通过触摸在屏幕上绘制形状的应用程序。
我可以从一个点到另一个点画一条线,但每次新画时它都会被擦除。
这是我的代码:
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;
}
感谢您的帮助 -
Nir。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所发现的,-drawRect 是显示视图内容的地方。您只能在屏幕上“看到”您在此处绘制的内容。
这比 Flash 之类的东西要低级得多,在 Flash 中,您可能会向舞台添加一个包含一行的影片剪辑,一段时间后将另一个包含一行的影片剪辑添加到舞台,现在您会看到 - 两行!
您将需要做一些工作,并且可能需要设置类似的东西。
我想您可以看到如何将其充实到您需要的内容。
解决此问题的另一种方法是使用 CALayers。使用这种方法,您根本不需要在内部绘制 - (void)drawRect - 您可以添加和删除图层,在其中绘制您喜欢的内容,视图将处理将它们合成在一起并根据需要绘制到屏幕上。可能更多的是您正在寻找的东西。
As you have discovered, -drawRect is where you display the contents of a view. You will only 'see' on screen what you draw here.
This is much more low-level than something like Flash where you might add a movieclip containing a line to the stage and some time later add another movieclip containing a line to the stage and now you see - two lines!
You will need to do some work and prdobably set up something like..
I think you can see how to flesh this out to what you need.
Another way to approach this is to use CALayers. Using this approach you dont draw inside - - (void)drawRect at all - you add and remove layers, draw what you like inside them, and the view will handle compositing them together and drawing to the screen as needed. Probably more what you are looking for.
每次调用
drawRect
时,您都会从一张白纸开始。如果您不记录之前绘制的所有内容以便再次绘制,那么您最终只会绘制手指的最新滑动,而不是任何旧的滑动。您必须跟踪所有手指滑动操作,以便在每次调用drawRect
时重新绘制它们。Every time that
drawRect
is called, you start with a blank slate. If you don't keep track of everything you have drawn before in order to draw it again, then you end up only drawing the latest swipe of your finger, and not any of the old ones. You will have to keep track of all of your finger swipes in order to redraw them every timedrawRect
is called.您可以绘制图像,然后在
drawRect:
方法中显示该图像,而不是重新绘制每一行。图像将为您累积线条。当然,这种方法使得undo的实现更加困难。来自iPhone应用程序编程指南:
Instead of redrawing every line, you can draw into an image and then just display the image in your
drawRect:
method. The image will accumulate the lines for you. Of course, this method makes undo more difficult to implement.From the iPhone Application Programming Guide: