java button 背景色_以编程方式删除UIButton背景颜色

我在ios7中遇到了自定义UIButton子类的问题 . 我想要做的是在nib文件中添加一个按钮,并在界面构建器中设置其背景颜色 . 在IB中,我将其类设置为自定义UIButton子类:MyShapeButton . 然后,使用我的UIButton子类(MyShapeButton)中的drawRect()函数绘制一个用该背景颜色填充的自定义按钮形状 . 我可以完成所有这些工作,但真正的问题是我无法从按钮中删除原始背景颜色,使其透明 . 所以 . 我的形状被绘制,但原始的背景颜色使它模糊不清 .

请注意以下内容:我的按钮类型设置为自定义,因为其他SO帖子说这很重要 . 它没有帮助 .

这是我的子类的drawRect代码:

- (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);

}

谢谢您的帮助 .

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值