Drawing multiple objects in quartz [basics]

Discussion in 'iOS Programming' started by ireman, May 6, 2010.

  1. ireman macrumors newbie

    Joined:
    May 6, 2010
    #1
    I want to make a simple program: the user touches the screen, and wherever he touches, there appears a rectangle. (old rectangles don't disappear) This has been bugging me for three days an the fact that Quartz is so poorly documented doesn't help. Anyway, I'd like for someone to write the two methods: touchesEnded (to add the new rectangle where the touch was to the array/list/something) and drawRect (to draw everything). Also perhaps point out that I need something more, but that would be surprising.
    It shouldn't take more than ten lines of each code each, so please help me.
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    First, we need to discuss the terms of payment... :D
     
  3. ireman thread starter macrumors newbie

    Joined:
    May 6, 2010
    #3
    I have a better idea. I'll post my code and someone will tell me what's wrong.

    Code:
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
      UITouch *touch = [touches anyObject];
      lastTouch = [touch locationInView:self];  
      npoints++;
      points = (CGRect *)malloc(sizeof(CGRect) * npoints);
      CGRect newRect = CGRectMake(lastTouch.x, lastTouch.y,30,30);
      points[points-1] = newRect;
      [self setNeedsDisplay];
    }
    
    - (void)drawRect:(CGRect)rect 
    {
      CGContextRef context = UIGraphicsGetCurrentContext();
      
      CGContextSetLineWidth(context, 2.0);
      CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
      CGContextSetFillColorWithColor(context, pointColor.CGColor);
      
      for(int i=0; i<npoints; i++)
      {
        CGContextFillRect(context, points[i]);
      }
    }
    According to the debugging info, the rects are stored properly, but their sizes randomly go haywire in the for loop in drawRect.
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    First,
    Code:
    points[npoints-1] = newRect;
    Second, when you malloc the block you don't copy in all the existing rects. Maybe you should use realloc.
     
  5. ireman thread starter macrumors newbie

    Joined:
    May 6, 2010
    #5
    Jeepers creepers, right you are! Thanks!

    EDIT: The n/points issue was obviously a type done when I was refactoring the code by hand.
     

Share This Page