【问题标题】:Creating a UIButton in shape of the image given以给定图像的形状创建一个 UIButton
【发布时间】:2013-01-22 21:08:54
【问题描述】:

如何创建一个与给定图像形状相同的 UIButton。

我能够创建接近它的东西,但图像似乎不适合按钮。 我的要求是下面给出的图像。即;半圆

我用来创建按钮的代码如下。

我应该对下图进行哪些更改才能获得此按钮。 ps-add subview 在另一个类中完成..

btnStartGame  =[UIButton buttonWithType:UIButtonTypeCustom];
[btnStartGame setFrame:CGRectMake(60, 200, 200, 200)];

btnStartGame.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:30];
[btnStartGame setImage:
[UIImage imageNamed:@"Draw button.png"]  forState:UIControlStateNormal];

btnStartGame.titleLabel.textColor=[UIColor redColor];
btnStartGame.clipsToBounds = YES;
btnStartGame.layer.cornerRadius = 50;//half of the width
btnStartGame.layer.borderColor=[UIColor redColor].CGColor;
btnStartGame.layer.borderWidth=2.0f;

btnStartGame.tag=20;
btnStartGame.highlighted=NO;

【问题讨论】:

  • 我忘了说最重要的事情,点击按钮不应该超出图像之外...严格在图像内部..
  • 它只是我正在开发的一个小游戏的开始屏幕。点击此按钮后我必须转到主页。但是当我为此集成图形时,我遇到了这个问题,我可以创建一个类似的按钮,但现在的问题是,如果我点击按钮图像之外的部分(应该是按钮),它需要点击。请帮助

标签: ios ios5 uibutton uiimage


【解决方案1】:

虽然由另一个答案链接的 Jeff Lamarche 的解决方案工作正常,但它使用了大量内存,并且/或者做了很多工作:

  • 如果您在初始化程序中创建一次NSData,您最终会在每个按钮的生命周期内持有相对较大的内存块
  • 如果你让它瞬态,它在答案中完成的方式,那么你最终会在每次点击测试按钮时转换整个图像 - 处理数千个像素并在获取单个字节后丢弃结果!

事实证明,通过遵循this answer 中概述的方法,您可以更有效地执行此操作,无论是在内存使用还是 CPU 消耗方面。

子类UIButton,并像这样覆盖它的pointInside:withEvent:方法:

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if (![super pointInside:point withEvent:event]) {
        return NO;
    }
    unsigned char pixel[1] = { 0 };
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 1, NULL, (CGBitmapInfo)kCGImageAlphaOnly);
    UIGraphicsPushContext(context);
    UIImage *image = [self backgroundImageForState:UIControlStateNormal] ;
    [image drawAtPoint:CGPointMake(-point.x, -point.y)];
    UIGraphicsPopContext();
    CGContextRelease(context);
    return pixel[0] != 0;
}

上面的代码从按钮的背景图像中获取 alpha。如果您的按钮使用其他图像,请更改上面初始化 image 变量的行。

【讨论】:

    【解决方案2】:

    这里有一个非常棒的教程,可下载源代码:

    http://iphonedevelopment.blogspot.co.uk/2010/03/irregularly-shaped-uibuttons.html

    本质上你需要在 UIImage 上创建一个类别,它检查你触摸的点是否是透明图像。这意味着您可以使用它来检查不规则形状的命中测试。

    然后你继承 UIButton 并覆盖 hitTest:withEvent:

    希望对你有帮助

    【讨论】:

    • 伟大的教程老兄......它工作得很好。我从程序中复制了 2 个类 OBShapedButton 和 UIImage+ColorAtPixel,将它们导入我的程序并制作按钮作为“OBShapedButton 类”的实例。它只检测到图像,我提到的问题没有发生。我还在上面给出的代码中评论了以下几行。
    • btnStartGame.clipsToBounds = YES; btnStartGame.layer.cornerRadius = 50;//宽度的一半 btnStartGame.layer.borderColor=[UIColor redColor].CGColor; btnStartGame.layer.borderWidth=2.0f;任何人都可以使用此方法创建任何形状的按钮。按照教程并喜欢我所做的事情。就这么简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多