【问题标题】:UIView with Png image - ignore touch in transparent areas带有 Png 图像的 UIView - 忽略透明区域中的触摸
【发布时间】:2011-07-16 00:46:00
【问题描述】:

我有一个带有透明背景的圆形 PNG 作为子视图添加。我正在使用这种类型的方法来旋转它:

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

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

}

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

谢谢!

【问题讨论】:

  • 我不知道面具的形状,但如果它很小:知道有些用户的手指真的很胖。 :)
  • 目前还没有面具。这只是一种看法。 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { UIImage *image1 = [UIImage imageNamed:@"nav@2x.png"]; wheelfrom = [[UIImageView alloc] initWithImage:image1]; wheelfrom.frame =CGRectMake(10, -130, 300, 300); [self addSubview:wheelfrom]; } 返回自我;有没有办法掩盖圆圈?

标签: iphone xcode transparency alpha


【解决方案1】:

您可以检查图像的 rbga 像素颜色,并查看 a(=alpha 值)是否 == 0(或

但在你的情况下它可能更容易...... 您使用的是 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!!");
        }
    }

【讨论】:

  • 感谢您的回复... 那还会使用 CGRectContainsPoint 函数吗?我会四处寻找二维解决方案,谢谢!
  • 您知道任何可以阐明半径检查的示例代码吗?
  • 哇,非常感谢!我正在试一试,但非常感谢您发布此消息!
  • 说真的,你帮了我很大的忙,它工作得很好。我真的很感激!
【解决方案2】:

快速解决方案:

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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 2013-06-26
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多