Pages

Showing posts with label Detect. Show all posts
Showing posts with label Detect. Show all posts

Saturday, August 3, 2013

Touch Detection inside Polygon Shape xCode

Suppose you have some polygon shape like the above pic and you need to find the touch inside this shape.

For this i have made my own logic from various sources and this code is as below


-(BOOL)pointInPolygon:(int)xPos andY:(int) yPos andPolyArray:(NSArray *)poly
{
    int j = poly.count - 1;
    BOOL oddNodes = false;
    for (int i = 0; i <poly.count; i++) {
        NSValue *val = [poly objectAtIndex:i];
        CGPoint pi = [val CGPointValue];
        
        val = [poly objectAtIndex:j];
        CGPoint pj = [val CGPointValue];
        
        if ((pi.y < yPos && pj.y >= yPos) ||  (pj.y < yPos && pi.y >= yPos)) {
            if (pi.x + (yPos - pi.y) / (pj.y - pi.y) * (pj.x - pi.x) <xPos) {
                oddNodes = !oddNodes;
            }
        }
        j = i;
    }
    return oddNodes;
}

In this function you just need to pass X and Y position of Touch location, with the polygon co-ordinates Array.

Now how to create a Polygon Shape Array?

Here is the solution of this, to define a Polygon Shape points

self.trackArea = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(412,0)],
                  [NSValue valueWithCGPoint:CGPointMake(827,0)],
                  [NSValue valueWithCGPoint:CGPointMake(210,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,513)],
                  
                  nil];


Now How to call, So here is that

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    if([self pointInPolygon:touchPoint.x andY:touchPoint.y andPolyArray:self.track1Area])
    {
        NSLog(@"Touch Detected for polygon");
    }
}

Add Image from URL in UIView and make clickable

I have made a sample code for this example

Step 1 - Load Image from URL

     UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"screen.png"]];

  [self.completeSingleView addSubview:imageView];

Step 2 - Now to make this clickable just use the following code

    imageView.userInteractionEnabled = YES;
   imageView.tag = 2;

Step 3 - Now to add this in any UIView. Follow the code below

     [self.completeSingleView addSubview:imageView];

Step 4- Now to detect the Image in touch began event, follow the code below


-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    UITouch *touch = [touches anyObject];
    if([touch.view tag] == 2)
        NSLog(@"Your Image is Touched");
}