cocoa触摸 – 自定义UIButton形状

我怎样才能使可触摸的button区域与所提供的图像具有相同的形状?
说我有一个三angular形图像的自定义button,我怎样才能确保只有在该三angular触摸将被处理。

或者我必须在触摸动作function中做一些math运算?

OBShapedButton是一个伟大的项目

它的工作原理是-pointInside:withEvent: UIButton并覆盖-pointInside:withEvent:

 @implementation OBShapedButton // UIView uses this method in hitTest:withEvent: to determine which subview // should receive a touch event. // If pointInside:withEvent: returns YES, then the subview's hierarchy is // traversed; otherwise, its branch // of the view hierarchy is ignored. - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { // Return NO if even super returns NO (ie if point lies outside our bounds) BOOL superResult = [super pointInside:point withEvent:event]; if (!superResult) { return superResult; } // We can't test the image's alpha channel if the button has no image. // Fall back to super. UIImage *buttonImage = [self imageForState:UIControlStateNormal]; if (buttonImage == nil) { return YES; } CGColorRef pixelColor = [[buttonImage colorAtPixel:point] CGColor]; CGFloat alpha = CGColorGetAlpha(pixelColor); return alpha >= kAlphaVisibleThreshold; } @end 

[aUIImage colorAtPixel:point]是附加的类别方法。

这个function绝对不是由与UIButton相关的核心cocoa触摸类提供的。 我想你会不得不考虑子类化UIButton和截取你所提到的水龙头。

Ole的OBShapedButton项目应该在SO上引用。 感谢vikingosegundo,过去曾经帮助过我的程序devise的例子 github,您可以看到一些Ole将什么东西从UIButton的透明背景部分拿走。 我把这个添加到我的项目,并能够得到它并与这些步骤运行。

  1. 下载该项目
  2. 将UIImage + ColorAtPixel.h / m和OBShapedButton.h / m文件添加到您的项目文件夹
  3. 确保.m文件被添加到目标的“构build阶段”>“编译源”列表中
  4. 将所有button的UIButton类types更改为IB中的OBShapedButton类
  5. 确保你的.png文件有一个透明的背景,并使其成为button的“图像”

这个项目可以帮助任何具有多个重叠UIButtons并具有透明背景的人,即使他们在不同的UIViews中,或者被另一个UIButton完全覆盖(例如,如果没有Editor> Arrange> Send to Back / Front,你不能在IB中select它) 。 但是,如果您在UIView中有一个OBShapedButton,其中透明UIView的一部分与OBShapedButton重叠,则无法在OBShapedButton的UIView覆盖部分上接收到单击或拖动事件,因此请牢记层叠您的UIViews。

下载Ole和维京的项目为您的教程收集……做它!