Thursday, August 11, 2011

How to find quadrant of touchpoint in your Arc ?

If you have created piechart like following using CGContextAddArc  using anti-clockwise method. Now if you want to find out which piece of pie you have touched , then you will need to find out quadrant.

We will follow normal quadrant convention in our library code.

Pie chart with quadrant division





















We will find the touchpoint on the view by following code


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   
    
    
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint=[touch locationInView:self];
    int quadrant=[self findQuadrant:touchPoint];


}


-(int)findQuadrant:(CGPoint)touchPoint
{
    //top right
    CGRect rect=CGRectMake(_centerX, 0, radius,_centerY );
    BOOL contains = CGRectContainsPoint(rect, touchPoint);
    if(contains)
        return 1;
    
    
    //top left
    rect=CGRectMake(0, 0, radius+ offsetX, _centerY);
    contains = CGRectContainsPoint(rect, touchPoint);
    if(contains)
        return 2;
    
    //bottom left
    rect=CGRectMake(0, _centerY, radiusoffsetX, _centerY);
    contains = CGRectContainsPoint(rect, touchPoint);
    if(contains)
        return 3;
    
    
    //bottom right
    rect=CGRectMake(_centerX, _centerY, radius, _centerY);
    contains = CGRectContainsPoint(rect, touchPoint);
    if(contains)
        return 4;
    
    
    //If the touch point doesn't lie in any of the quadrants return 0
    return 0;
}






In the code above offsetX is the distance from the left edge of view and left most point of the piechart circumference. In the above image of piechart, it is about 5 px. radius is the radius of the arc. and (_centerX, _centerY) is the center point of arc in the view.

No comments:

Post a Comment