简体   繁体   English

如何制作带有阴影的半透明按钮?

[英]How to make semi-transparent button with shadow?

I have a UIButton, that needs to be white and 50% transparent. 我有一个UIButton,它需要为白色且透明度为50%。 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]. 同样,UIColor初始化程序接受范围为[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: 样品按钮:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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