简体   繁体   中英

UIButton shadow and lighting effect (Swift 4)

I'd like to add a lighting effect like these two buttons, a shadow on the bottom but also a lighted edge on top as if there were a light above it.

在此处输入图片说明

I've been experimenting with :

button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowColor.layer.shadowOffset = CGSize(width: 2, height: 2)
button.layer.shadowColor.layer.shadowRadius = 2
button.layer.shadowColor.layer.shadowOpacity = 8
button.layer.shadowColor.layer.masksToBounds = false

and get a nice shadow on the bottom, but how would I light up the top edge?

I was able to get a button pretty similar to your first drawing, just as an experiment:

在此处输入图片说明

The button background is constructed entirely using elementary drawing commands involving UIBezierPath and CGContext in a UIGraphicsImageRenderer. So if that's an acceptable sort of approach, you could just do a tweak on the sort of thing I'm doing.

let r = UIGraphicsImageRenderer(size: CGSize(width:100, height:100))
let im = r.image {
    ctx in let con = ctx.cgContext
    do {
        let p = UIBezierPath(roundedRect: CGRect.init(x: 0, y: 0, width: 100, height: 50), cornerRadius: 10)
        UIColor(white: 0.9, alpha: 1.0).setFill()
        p.fill()
    }
    do {
        let p = UIBezierPath(roundedRect: CGRect.init(x: 0, y: 50, width: 100, height: 50), cornerRadius: 10)
        UIColor(white: 0.1, alpha: 1.0).setFill()
        p.fill()
    }
    do {
        let p = UIBezierPath(roundedRect: CGRect.init(x: 0, y: 2, width: 100, height: 95), cornerRadius: 10)
        p.addClip()
    }
    let locs : [CGFloat] = [ 0.0, 0.2, 0.8, 1.0 ]
    let colors : [CGFloat] = [
        0.54, 0.54, 0.54, 1.0,
        0.5, 0.5, 0.5, 1.0,
        0.5, 0.5, 0.5, 1.0,
        0.44, 0.44, 0.44, 1.0,
    ]
    let sp = CGColorSpaceCreateDeviceRGB()
    let grad = CGGradient(
        colorSpace:sp, colorComponents: colors, locations: locs, count: 4)!
    con.drawLinearGradient(grad,
                           start: CGPoint(x:0,y:0), end: CGPoint(x:0,y:100), options:[])
}
let b = UIButton(type: .custom)
b.setTitle("9", for: .normal)
b.setBackgroundImage(im, for: .normal)
b.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
b.titleLabel?.font = UIFont.systemFont(ofSize: 40, weight: .bold)
self.view.addSubview(b)
b.layer.borderWidth = 1
b.layer.borderColor = UIColor.black.cgColor
b.layer.cornerRadius = 10

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