programatically remove UIButton background color

I'm having a problem with a custom UIButton subclass in ios7. What I want to do is add a button to a nib file and set its background color in interface builder. In IB, I set its class to a custom UIButton subclass: MyShapeButton. Then, use the drawRect() function in my UIButton subclass (MyShapeButton) to draw a custom button shape that is filled with that background color. I can get all of that working, but the real issue is that I can't remove the original background color from the button, making it transparent. So. my shape is drawn, but the original background color obscures it.

Please note the following: my button type is set to custom, since other SO posts said this was important. It did not help.

here's the drawRect code from my subclass:

- (void)drawRect:(CGRect)rect
{
    UIColor* buttonColor = self.backgroundColor;

//========= this doesn't work =========
    [self setBackgroundColor:[UIColor clearColor]];


    CGFloat width = rect.size.width;
    CGFloat height = rect.size.height;
    CGFloat radius = 10;
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(context, 0, height); //bottom left
    CGContextAddLineToPoint(context, 0, radius);
    CGContextAddArcToPoint(context, 0, 0, radius, 0, radius);
    CGContextAddLineToPoint(context, width, 0);
    CGContextAddLineToPoint(context, width, height-radius);
    CGContextAddArcToPoint(context, width, height, width-radius, height, radius);
    CGContextAddLineToPoint(context, 0, height);

    //shape is drawn here, but you can't see it:
    CGContextSetFillColorWithColor(context, buttonColor.CGColor);

    //uncomment this to see the button shape
    //CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);

    CGContextFillPath(context);


}

Thanks for the help.

UPDATE: here is the working code for drawRect():

- (void)drawRect:(CGRect)rect
{
    CGFloat radius = 10.f;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds                                                  byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight
                                                       cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

I think you should use another CALayer with bezier path as mask to crop your button background. see examples here

  • Stroke masked CALayer in iOS
  • Create layer mask with custom-shaped hole
  • 链接地址: http://www.djcxy.com/p/74268.html

    上一篇: 地图的自定义注释视图

    下一篇: 以编程方式删除UIButton背景颜色