Search code examples
iphonexcodetransparencyalpha

UIView with Png image - ignore touch in transparent areas


I have a PNG of a circle with a transparent background added as a subview. I'm using this type of method to rotate it:

CGPoint location = [touch locationInView:self.view];

if(CGRectContainsPoint(wheelfrom.frame, location))
{

}

the problem is that the transparent area's of the image are registering as part of the UIView. Is there a way to ignore those area's when touched? Is there a better way for me to set up the UIView to recognize the transparency?

thanks!


Solution

  • you can check the rbga pixel colour of the image and see if a (=alpha value) is == 0 (or <= aLowValue)... as suggested by Igor Pchelko...

    but in your case it may be easier... you are using a 2D circle, so just check how the finger click is far from the circle center and see if it's out of its radius... just a Pitagora's theorem application...

    EDIT:

    ok, so, if you create a new class for your button subclassing UIButton:

    in YourButton.h:

    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    
    @interface YourButton : UIButton {
    
    }
    
    @end
    

    in YourButton.m just add this code:

        - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
            UITouch *touch = [[event allTouches] anyObject];
            CGPoint touchPoint = [touch locationInView:self];
            NSLog(@"Touch x : %f y : %f", touchPoint.x, touchPoint.y);
            float circleRadius = self.frame.size.height / 2; // considering a circle inscricted in a quadRect (width = height)
            float deltaTouchOnCenterX = touchPoint.x - circleRadius;
            float deltaTouchOnCenterY = touchPoint.y - circleRadius;
            float touchDistanceFromCenter = sqrt((deltaTouchOnCenterX * deltaTouchOnCenterX) + (deltaTouchOnCenterY * deltaTouchOnCenterY) );
    // or:  float touchDistanceFromCenter = hypot(deltaTouchOnCenterX,deltaTouchOnCenterY);
    
            NSLog(@"sqrt_val: %f", touchDistanceFromCenter);
            NSLog(@"Touch on center x : %f y : %f", deltaTouchOnCenterX, deltaTouchOnCenterY);
            if (touchDistanceFromCenter <= circleRadius) {
                // your code here
                NSLog(@"___ OK: You are inside the circle!!");
            }
        }