View Full Version : How keep drawing from disappearing with setNeedsDisplay?

Mar 29, 2011, 08:20 PM
I am trying to have it so when the user taps the screen, a small point appears at that touched point. I need it so that the drawn point remains on the screen in its position instead of being completely redrawn at the new point the user taps the second time, or third time, etc. So basically every time the user taps the screen a point shows at that point and does not disappear the next time the user taps the screen and a new point is made. Here's my code so far:

- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextFillEllipseInRect(context, CGRectMake(point1.x - 5,point1.y - 5, 10, 10));

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextDrawPath(context, kCGPathFillStroke);


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

UITouch *touch = [touches anyObject];

point1 = [touch locationInView:self];
point1xCoordinate = point1.x;
point1yCoordinate = point1.y;
[self setNeedsDisplay];

Any help is very much appreciated.

Mar 29, 2011, 09:54 PM
In a MVC design your view draws the data and your model stores the data. You need a data model that stores ALL of the points and your view needs to be able to draw ALL of the points.

Mar 29, 2011, 10:16 PM
would you happen to know how I can do that? I know it's frustrating to deal with a noob, trust me, but i am new and trying to learn

Mar 29, 2011, 10:38 PM
I haven't written this exact code so I don't know for sure. You need some kind of list that stores the x,y coordinates in it. Then the drawing code needs to iterate over all the points in the list and draws each one. It could be a mutable array of points. Do you have an idea of how many points would be the maximum that would exist? Problem is that CGPoint isn't an object so can't be directly stored in a mutable array. You could use every two items in an array for the x and then y coordinate. Store NSNumbers for the x and y values.

It's also possible to to use NSValue to store a CGPoint or it's possible to convert a CGPoint to/from a string using the functions in UIGeometry.h.

You could write a simple NSObject subclass that has an x and y ivar and store those in your array.

All of these strategies will work but are a little inefficient since you can't store CGFloats directly in an array.