我想在此UIlabel中添加内部阴影
照片:
参考表格Inner shadow effect on UIView layer?
let display = UILabel()
func setBackgroundLayer () {
let backgroundLayer = CAGradientLayer()
backgroundLayer.frame = view.bounds
backgroundLayer.colors = [UIColor(white:1,alpha:0.5).cgColor,UIColor(white:0.5,alpha:0.5).cgColor]
view.layer.insertSublayer(backgroundLayer, at: 0)
}
func setDisplay() {
let Xratio = view.bounds.width/8
display.frame = CGRect(x:Xratio,y:80,width:Xratio*6,height:Xratio*2)
display.backgroundColor = UIColor(red:204/255,green:203/255,blue:181/255,alpha:1)
view.addSubview(display)
}
func displayInnerShadow() {
let shadowLayer = CAShapeLayer()
shadowLayer.frame = view.bounds
let path = CGMutablePath()
path.addRect(display.frame.insetBy(dx: -20, dy: -20))
path.addRect(display.frame)
shadowLayer.fillRule = kCAFillRuleEvenOdd
shadowLayer.path = path
shadowLayer.shadowColor = UIColor(white:0,alpha:1).cgColor
shadowLayer.shadowOffset = CGSize(width:0,height:0)
shadowLayer.shadowOpacity = 1
shadowLayer.shadowRadius = 5
view.layer.insertSublayer(shadowLayer, at: 1)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setBackgroundLayer()
setDisplay()
//displayInnerShadow()
}
我得到了这个结果:
为什么它不起作用以及如何设置填充颜色?
答案 0 :(得分:2)
试试这个
let display = UILabel()
func setBackgroundLayer () {
let backgroundLayer = CAGradientLayer()
backgroundLayer.frame = view.bounds
backgroundLayer.colors = [UIColor(white:1,alpha:0.5).cgColor,UIColor(white:0.5,alpha:0.5).cgColor]
view.layer.insertSublayer(backgroundLayer, at: 0)
}
func setDisplay() {
let Xratio = view.bounds.width/8
display.frame = CGRect(x:Xratio,y:80,width:Xratio*6,height:Xratio*2)
设置图层背景颜色而不是display.backgroundColor
display.layer.backgroundColor = UIColor(red:204/255,green:203/255,blue:181/255,alpha:1).cgColor
view.addSubview(display)
}
func displayInnerShadow() {
let innerShadowLayer = CALayer()
innerShadowLayer.frame = display.bounds
let path = UIBezierPath(rect: innerShadowLayer.bounds.insetBy(dx: -20, dy: -20))
let innerPart = UIBezierPath(rect: innerShadowLayer.bounds).reversing()
path.append(innerPart)
innerShadowLayer.shadowPath = path.cgPath
innerShadowLayer.masksToBounds = true
innerShadowLayer.shadowColor = UIColor.black.cgColor
innerShadowLayer.shadowOffset = CGSize.zero
innerShadowLayer.shadowOpacity = 1
innerShadowLayer.shadowRadius = 5
display.layer.addSublayer(innerShadowLayer)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setDisplay()
setBackgroundLayer()
displayInnerShadow()
}