2010-11-12 62 views
3

如何使可触摸按钮区域与所提供图像的形状相同?
说我有一个三角形图像的自定义按钮,我怎么才能确保只有在该三角内的触摸将被处理。Cocoa Touch - 自定义UIButton形状

或者我必须在触摸动作功能中做某种算术吗?

+0

我你决定拦截水龙头,苹果已经为你做了所有的数学。查看'UIBezierPath'的containsPoint:'方法(http://developer.apple.com/library/ios/documentation/uikit/reference/UIBezierPath_class/Reference/Reference.html#//apple_ref/occ/instm/UIBezierPath/ containsPoint :) – cobbal 2010-11-12 06:01:12

回答

1

此功能绝对不是由与UIButton相关的核心可可触摸类提供的。我想你会不得不考虑子类化UIButton并拦截你提到的水龙头。

3

OBShapedButton是针对

一个伟大的项目它的工作原理通过继承的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 (i.e. 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]是连接一个类别的方法。

1

Ole的OBShapedButton项目应该在SO上引用更多。感谢vikingosegundo,github曾帮助过my-programming-examples,你可以看到一些Ole将什么东西从定制的UIButton的透明背景部分拿走。我将它添加到了我的项目中,并能够通过这些步骤启动并运行它。

  1. 下载项目
  2. 文件添加的UIImage + ColorAtPixel.h/m和OBShapedButton.h/m到项目文件夹
  3. 确保.m文件添加到您的目标的构建阶段>编译源列表
  4. 变化IB的UIButton的类类型所有的按钮将OBShapedButton类
  5. 确保您的PNG文件具有透明背景,使之成为该按钮的“图像”

这个项目将帮助任何具有多个重叠的UIButtons的具有透明背景的人,即使他们在不同的UIViews中或完全由另一个UIButton覆盖(例如,如果没有Editor> Arrange> Send> Send /面前)。但是,如果在UIView中有一个OBShapedButton,其中透明UIView的一部分与OBShapedButton重叠,则无法在OBShapedButton的UIView覆盖部分接收到单击或拖动事件,因此请牢记层层设置UIView。

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