gpt4 book ai didi

白色背景上带有透明标题的 iOS UIButton

转载 作者:可可西里 更新时间:2023-11-01 03:54:14 25 4
gpt4 key购买 nike

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

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

如果不是,你能告诉我如何反转 CALayer alpha 吗?

最佳答案

您可以使用 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 而不是仅仅将它添加到 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com