使用Png图像的UIView - 忽略透明区域中的触摸

时间:2011-03-15 18:22:35

标签: iphone xcode transparency alpha

我有一个圆圈的PNG,透明背景被添加为子视图。我正在使用这种方法来旋转它:

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

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

}

问题是图像的透明区域是作为UIView的一部分注册的。触摸时有没有办法忽略这些区域?有没有更好的方法让我设置UIView来识别透明度?

谢谢!

3 个答案:

答案 0 :(得分:2)

你可以检查图像的rbga像素颜色,看看(= alpha值)是否= = 0(或< = aLowValue)......正如Igor Pchelko建议的......

但在你的情况下它可能会更容易...... 你正在使用一个2D圆圈,所以只需检查手指点击远离圆心的方式,看看它是否超出了它的半径......只是一个Pitagora的定理应用......

修改

好的,所以,如果你为你的按钮创建了一个新类UIButton:

在YourButton.h中

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface YourButton : UIButton {

}

@end
在YourButton.m中

只需添加以下代码:

    - (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!!");
        }
    }

答案 1 :(得分:0)

尝试测试UIImage(圆圈或其他)的不透明度像素。

要查看像素颜色,请参阅: How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

答案 2 :(得分:0)

快速解决方案:

class RadiusTouchButton: UIButton {
  override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let radius = frame.size * 0.5
    let delta = point - CGPoint(x: radius.height, y: radius.width)
    return hypot(delta.x, delta.y) <= radius.height
  }
}