Draw a perfect circle from user's touch

后端 未结 7 1675
天命终不由人
天命终不由人 2021-01-29 17:28

I have this practice project that allows the user to draw on the screen as they touch with their fingers. Very simple App I did as exercise way back. My little cousin took the l

7条回答
  •  暖寄归人
    2021-01-29 17:44

    Here is another way. Using UIView touchesBegan, touchesMoved, touchesEnded and adding points to an array. You divide the array into halves, and test whether every point in one array is roughly the same diameter from its counterpart in the other array as all of the other pairs.

        NSMutableArray * pointStack;
    
        - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
        {
            // Detect touch anywhere
        UITouch *touch = [touches anyObject];
    
    
        pointStack = [[NSMutableArray alloc]init];
    
        CGPoint touchDownPoint = [touch locationInView:touch.view];
    
    
        [pointStack addObject:touchDownPoint];
    
        }
    
    
        /**
         * 
         */
        - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
        {
    
                UITouch* touch = [touches anyObject];
                CGPoint touchDownPoint = [touch locationInView:touch.view];
    
                [pointStack addObject:touchDownPoint];  
    
        }
    
        /**
         * So now you have an array of lots of points
         * All you have to do is find what should be the diameter
         * Then compare opposite points to see if the reach a similar diameter
         */
        - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
        {
                uint pointCount = [pointStack count];
    
        //assume the circle was drawn a constant rate and the half way point will serve to calculate or diameter
        CGPoint startPoint = [pointStack objectAtIndex:0];
        CGPoint halfWayPoint = [pointStack objectAtIndex:floor(pointCount/2)];
    
        float dx = startPoint.x - halfWayPoint.x;
        float dy = startPoint.y - halfWayPoint.y;
    
    
        float diameter = sqrt((dx*dx) + (dy*dy));
    
        bool isCircle = YES;// try to prove false!
    
        uint indexStep=10; // jump every 10 points, reduce to be more granular
    
        // okay now compare matches
        // e.g. compare indexes against their opposites and see if they have the same diameter
        //
          for (uint i=indexStep;i=(diameter-10) && testDiameter<=(diameter+10)) // +/- 10 ( or whatever degree of variance you want )
          {
          //all good
          }
          else
          {
          isCircle=NO;
          }
    
        }//end for loop
    
        NSLog(@"iCircle=%i",isCircle);
    
    }
    

    That sound okay? :)

提交回复
热议问题