Garik Israyelyan
Garik Israyelyan

Reputation: 11

How to add a glowing effect with shadow to a gradient border in a Swift app?

I am currently developing a Swift app and I have managed to create a border with a gradient color. However, I am trying to enhance the look of the border by adding a glowing effect along with a shadow. Here's the code snippet I have so far:

var gradientCGColors: [CGColor] = [
    NSColor(red: 64/255, green: 255/255, blue: 140/255, alpha: 1.0).cgColor,
    NSColor(red: 0/255, green: 178/255, blue: 255/255, alpha: 1.0).cgColor,
    NSColor(red: 153/255, green: 72/255, blue: 255/255, alpha: 1.0).cgColor
]

class GradientBorderView: NSView {
    var gradientCGColors: [CGColor] = [
        NSColor(red: 64/255, green: 255/255, blue: 140/255, alpha: 1.0).cgColor,
        NSColor(red: 0/255, green: 178/255, blue: 255/255, alpha: 1.0).cgColor,
        NSColor(red: 153/255, green: 72/255, blue: 255/255, alpha: 1.0).cgColor
    ]

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        guard let context = NSGraphicsContext.current?.cgContext else { return }

        let gradient = CGGradient(colorsSpace: nil, colors: gradientCGColors as CFArray, locations: nil)
        let borderFrame = bounds.insetBy(dx: 2, dy: 2) 

        context.saveGState()
        context.addRect(bounds)
        context.addRect(borderFrame)
        context.clip(using: .evenOdd)

        let startPoint = CGPoint(x: bounds.midX, y: bounds.minY)
        let endPoint = CGPoint(x: bounds.midX, y: bounds.maxY)
        context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [])
        context.restoreGState()

        addNeonEffect()
    }
    
    private func addNeonEffect() {
        self.wantsLayer = true
        let shadow = NSShadow()
        shadow.shadowColor = NSColor.white.withAlphaComponent(1.0)
        shadow.shadowBlurRadius = 40 // Increased radius for a lot of shadow
        shadow.shadowOffset = .zero
        self.shadow = shadow
    }
}

In the GradientBorderView class, I create a gradient with colors defined in gradientCGColors and apply it to the border. I also attempt to add a glowing effect in the addNeonEffect() function by setting a shadow with white color and a large blur radius.

My goal is to make the gradient border have a glowing effect with much shadow. I basically need to achieve something similar to this, if it was CSS:

h1 {
  box-shadow: 0 0 .2rem #fff,
            0 0 .2rem #fff,
            0 0 2rem #BC13FE,
            0 0 0.8rem #BC13FE,
            0 0 2.8rem #BC13FE,
            inset 0 0 1.3rem #BC13FE;
}

However, the current solution doesn't seem to provide the expected result. I would appreciate it if someone could guide me on how to achieve the desired effect. Thanks!

Upvotes: 1

Views: 293

Answers (0)

Related Questions