简体   繁体   中英

How to make semi-transparent button with shadow?

I have a UIButton, that needs to be white and 50% transparent. In the same time I need shadow. But shadow is a rectangle and it could be seen through button background. Is it possible to make something with that?

The code I have now:

self.WhiteBtn.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.9];
self.WhiteBtn.opaque = NO;

self.WhiteBtn.clipsToBounds = NO;

self.WhiteBtn.layer.shadowColor = [UIColor blackColor].CGColor;
self.WhiteBtn.layer.shadowOpacity = 0.5;
self.WhiteBtn.layer.shadowRadius = 5;
self.WhiteBtn.layer.shadowOffset = CGSizeMake(0,0);

There were 2 initial problems: the shape of the shadow (which was rectangular initially) and the button background color being blended with the shadow color. Also, the UIColor initializer accepts all the arguments in range [0.0, 1.0]. Finally, I made some more tweaks and got this (see both the code and a sample button below). Code:

    let shadowPathWidth: CGFloat = 1.0 // fine tune your shadow's width with this
    let layerAndShadowRadius: CGFloat = 5.0 //and its radius with this

    WhiteBtn.backgroundColor = UIColor(red:1, green:1, blue:1, alpha:0.9)
    WhiteBtn.layer.cornerRadius = layerAndShadowRadius
    WhiteBtn.layer.shadowPath = CGPathCreateCopyByStrokingPath(CGPathCreateWithRoundedRect(WhiteBtn.bounds, layerAndShadowRadius, layerAndShadowRadius, nil), nil, shadowPathWidth, CGLineCap.Round, CGLineJoin.Bevel, 0.0)

    WhiteBtn.layer.shadowOpacity = 1.0;
    WhiteBtn.layer.shadowOffset = CGSizeMake(0,0)

Sample button:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM