与透明标题的iOS UIButton在白色背景

时间:2014-05-07 10:20:59

标签: ios objective-c uibutton calayer alpha

我有一个带有透明背景和白色标题的自定义UIButton。 我正在寻找一个简单的解决方案,在高亮(白色背景和透明标题)上将其反转,因为它在系统UISegmentedControl上实现。

是否比在用作CALayer掩码的快照上反转alpha更简单?

如果没有,你能告诉我如何反转CALayer alpha?

2 个答案:

答案 0 :(得分:5)

您可以使用Destination Out作为混合模式在CGContext上绘制文本。

此代码似乎有效:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];

    UIFont* font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    NSString* buttonText = @"BUTTON";
    CGSize buttonSize =  CGSizeMake(200, 50);
    NSDictionary* textAttributes = @{NSFontAttributeName:font};

    CGSize textSize = [buttonText sizeWithAttributes:textAttributes];

    UIGraphicsBeginImageContextWithOptions(buttonSize, NO, [[UIScreen mainScreen] scale]);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, buttonSize.width, buttonSize.height)];
    CGContextAddPath(ctx, path.CGPath);
    CGContextFillPath(ctx);

    CGContextSetBlendMode(ctx, kCGBlendModeDestinationOut);
    CGPoint center = CGPointMake(buttonSize.width/2-textSize.width/2, buttonSize.height/2-textSize.height/2);
    [@"BUTTON" drawAtPoint:center withAttributes:textAttributes];


    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImageView* imgView = [[UIImageView alloc] initWithImage:viewImage];
    [self.view addSubview:imgView];
}

顺便说一句,如果你想在UIButton中设置UIImage而不是只是将它添加到视图中:

UIButton* boton = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, viewImage.size.width, viewImage.size.height)];
[boton setBackgroundColor:[UIColor clearColor]];
[boton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
boton.titleLabel.font = font;
[boton setTitle:buttonText forState:UIControlStateNormal];
[boton setImage:viewImage forState:UIControlStateHighlighted];
[self.view addSubview:boton];

答案 1 :(得分:0)

你可以设置

-(void)viewDidload: {
    [yourButton setTitleColor:(UIColor *)color 
                     forState:UIControlStateHighlighted];
    [yourButton addTarget:self 
                   action:@selector(changeButtonBackGroundColor:) 
         forControlEvents:UIControlEventTouchDown];
}

-(void)changeButtonBackGroundColor:(UIButton *)button {
    [button setBackgroundColor:[UIColor yourColor]];
}

请记住使用以下事件进行更改:UIControlEventTouchUpInsideUIControlEventTouchOutSide:)