Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIButton with transparent title on white background

I have a custom UIButton with transparent background and white title. I'm looking for a simple solution to invert it on highlight (white background and transparent title) as it is achieved on system UISegmentedControl.

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

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

like image 211
Krzysztof Przygoda Avatar asked May 07 '14 10:05

Krzysztof Przygoda


1 Answers

You can draw the text on a CGContext using Destination Out as blend mode.

This code seems to work:

- (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 set the UIImage in a UIButton instead of just adding it to a 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];
like image 114
Odrakir Avatar answered Oct 05 '22 23:10

Odrakir