Edou Suilen
Edou Suilen

Reputation: 7

Draw stuff on touch objective c

hy,

How can i make something that changes color when i touch it in objective c, i want the whole screen to be touchable and want to draw stuff on it with finger. Everywhere i touch it should change the color. Whats the best way to do it? I already have touchesMoved implemented to get the coordinates of the touch.

UITouch * touch = [touches anyObject];
CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];

Any example code would be nice thanks.

thank you in advance,

i have the following code but it doesnt print anything where i touch

-(void)setPaths:(NSMutableArray *)paths
{
    self.paths =[[NSMutableArray alloc]init];
}

-(void)setAPath:(UIBezierPath *)aPath
{
  self.aPath=[UIBezierPath bezierPath];
}

-(void) drawRect:(CGRect)rect{
    [super drawRect:rect];
    [[UIColor blackColor] set];
    for (UIBezierPath *path in paths) {
        [path stroke];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.paths addObject:self.aPath];

    //self.aPath=[UIBezierPath bezierPath];
}

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

    UITouch * touch = [touches anyObject];
    CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];
    [self.aPath addLineToPoint:[touch locationInView:self]];
    // [self.aPath addLineToPoint:[touch locationInView:touch]];

    NSLog(@"Position of touch: %.3f, %.3f", pos.x, pos.y);
}

@end

Upvotes: 0

Views: 213

Answers (2)

Alex Cio
Alex Cio

Reputation: 6052

Maybe you're going to change your drawRect: method. insert these 2 lines:

[[UIColor blackColor] setStroke];
[path stroke];

and you should add [self setNeedsDisplay]; after you've added a line inside touchesMoved:

I just passed following tutorial, it should solve your problem. It also explains how you can improve your code so it won't get too lazy if you're drawing longer lines: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/

Upvotes: 0

Antonio MG
Antonio MG

Reputation: 20410

When your touch starts, create a UIBezierPath:

self.myPath = [UIBezierPath bezierPath];

Then, every time the touches moves, add a point to the path:

 [self.myPath addLineToPoint:[touch locationInView:self]];

Once your touch has ended, in your drawRect just draw the path:

-(void) drawRect:(CGRect)rect{    
[super drawRect:rect];  
    [[UIColor blueColor] set];
    for (UIBezierPath *path in paths) {
          [path stroke];
    }
}

Find all the doc here:

UIBezierPath Class Reference

Upvotes: 2

Related Questions