IOS UIButton with transparent header on a white background.

I have a custom UIButton with a transparent background and a white name. I am looking for a simple solution to invert it to highlight (white background and transparent title), as is achieved in the UISegmentedControl system.

Is there a simpler solution than inverting the alpha snapshot used as a CALayer mask?

If not, could you say how can I invert CALayer alpha?

+6
source share
2 answers

You can draw text in a CGContext using Destination Out as an overlay mode.

This code works:

 - (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]; } 

By the way, if you want to install UIImage in UIButton, and not just add it to the view:

 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]; 
+5
source

You can set

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

don't forget to change it using events: UIControlEventTouchUpInside and UIControlEventTouchOutSide :)

0
source

All Articles