与透明标题的iOS UIButton在白色背景 [英] iOS UIButton with transparent title on white background

查看:229
本文介绍了与透明标题的iOS UIButton在白色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

推荐答案

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

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

此代码似乎有效:

- (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而不是只是将它添加到一个视图:

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

这篇关于与透明标题的iOS UIButton在白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆