透明的UIButton标题

时间:2014-12-13 11:04:32

标签: ios swift uibutton calayer

如何从按钮背景中减去标题文字的形状?

enter image description here

我创建了一个自定义UIButton类。目前,添加边框和文本颜色的代码看起来就像这样

layer.borderWidth = 2.0
layer.borderColor = buttonColor.CGColor
layer.cornerRadius = (CGFloat(bounds.height) + paddingVertical * 2.0) / 2.0
setTitleColor(buttonColor, forState: UIControlState.Normal)

关于如何从背景中减去按钮标题形状的任何建议。我是否需要将所有这些渲染为图像或是否有更好的替代方案?

4 个答案:

答案 0 :(得分:5)

我为你编写了一些代码,我的UIButton子类名为AKStencilButton(可在github https://github.com/purrrminator/AKStencilButton上找到):

#import "AKStencilButton.h"
#import <QuartzCore/QuartzCore.h>

@interface AKStencilButton ()
{
    UIColor * _buttonColor;
}
@end

@implementation AKStencilButton

-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]){
        [self setupDefaults];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]){
        [self setupDefaults];
    }
    return self;
}
-(void)setupDefaults
{
    self.backgroundColor = [UIColor redColor];
    self.layer.cornerRadius = 4;
    self.clipsToBounds = YES;
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    [self refreshMask];
}
-(void)setTitleColor:(UIColor *)color forState:(UIControlState)state
{
    [super setTitleColor:[UIColor clearColor] forState:state];
}
-(void)refreshMask
{
    self.titleLabel.backgroundColor = [UIColor clearColor];
    [self setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];

    NSString * text = self.titleLabel.text;
    CGSize buttonSize = self.bounds.size;
    UIFont * font = self.titleLabel.font;

    NSDictionary* attribs = @{NSFontAttributeName: self.titleLabel.font};
    CGSize textSize = [text sizeWithAttributes:attribs];


    UIGraphicsBeginImageContextWithOptions(buttonSize, NO, [[UIScreen mainScreen] scale]);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);
    CGPoint center = CGPointMake(buttonSize.width/2-textSize.width/2, buttonSize.height/2-textSize.height/2);

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

    [text drawAtPoint:center withAttributes:@{NSFontAttributeName:font}];
    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CALayer *maskLayer = [CALayer layer];
    maskLayer.contents = (__bridge id)(viewImage.CGImage);
    maskLayer.frame = self.bounds;
    self.layer.mask = maskLayer;
}
@end

它看起来像这样(对不起彩虹):

enter image description here

答案 1 :(得分:4)

我向UIView添加了以下方法来解决这个问题:

-(void)maskSubviews:(NSArray*)subviews {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextFillRect(context, self.bounds);

    CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
    for (UIView *view in subviews) {
        CGPoint origin = [view convertPoint:CGPointZero toView:self];
        CGContextTranslateCTM(context, origin.x, origin.y);
        [view.layer renderInContext:context];
        CGContextTranslateCTM(context, -origin.x, -origin.y);
    }
    UIImage* mask = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    self.maskView = [[UIImageView alloc] initWithImage:mask];
}

只需将您想要屏蔽的视图调用即可。例如:

[button maskSubviews: @[button.titleLabel, button.imageView]]

答案 2 :(得分:3)

swift 4的扩展程序

extension UIButton{
func clearColorForTitle() {

    let buttonSize = bounds.size

    if let font = titleLabel?.font{
        let attribs = [NSAttributedStringKey.font: font]

        if let textSize = titleLabel?.text?.size(withAttributes: attribs){
            UIGraphicsBeginImageContextWithOptions(buttonSize, false, UIScreen.main.scale)

            if let ctx = UIGraphicsGetCurrentContext(){
                ctx.setFillColor(UIColor.white.cgColor)

                let center = CGPoint(x: buttonSize.width / 2 - textSize.width / 2, y: buttonSize.height / 2 - textSize.height / 2)
                let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height))
                ctx.addPath(path.cgPath)
                ctx.fillPath()
                ctx.setBlendMode(.destinationOut)

                titleLabel?.text?.draw(at: center, withAttributes: [NSAttributedStringKey.font: font])

                if let viewImage = UIGraphicsGetImageFromCurrentImageContext(){
                    UIGraphicsEndImageContext()

                    let maskLayer = CALayer()
                    maskLayer.contents = ((viewImage.cgImage) as AnyObject)
                    maskLayer.frame = bounds

                    layer.mask = maskLayer
                }
            }
        }
    }
}

用法:

button.clearColorForTitle()

答案 3 :(得分:1)

我将@ purrrminator的解决方案转换为Swift 3,只是主要方法。

func clearTextButton(button: UIButton, title: NSString, color: UIColor) {
    button.backgroundColor = color
    button.titleLabel?.backgroundColor = UIColor.clear()
    button.setTitleColor(UIColor.clear(), for: .normal)
    button.setTitle(title as String, for: [])
    let buttonSize: CGSize = button.bounds.size
    let font: UIFont = button.titleLabel!.font
    let attribs: [String : AnyObject] = [NSFontAttributeName: button.titleLabel!.font]
    let textSize: CGSize = title.size(attributes: attribs)
    UIGraphicsBeginImageContextWithOptions(buttonSize, false, UIScreen.main().scale)
    let ctx: CGContext = UIGraphicsGetCurrentContext()!
    ctx.setFillColor(UIColor.white().cgColor)
    let center: CGPoint = CGPoint(x: buttonSize.width / 2 - textSize.width / 2, y: buttonSize.height / 2 - textSize.height / 2)
    let path: UIBezierPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height))
    ctx.addPath(path.cgPath)
    ctx.fillPath()
    ctx.setBlendMode(.destinationOut)
    title.draw(at: center, withAttributes: [NSFontAttributeName: font])
    let viewImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    let maskLayer: CALayer = CALayer()
    maskLayer.contents = ((viewImage.cgImage) as! AnyObject)
    maskLayer.frame = button.bounds
    button.layer.mask = maskLayer
}