提问人:Garik Israyelyan 提问时间:6/20/2023 最后编辑:Joakim DanielsonGarik Israyelyan 更新时间:6/20/2023 访问量:157
如何在 Swift 应用程序中为渐变边框添加带有阴影的发光效果?
How to add a glowing effect with shadow to a gradient border in a Swift app?
问:
我目前正在开发一个 Swift 应用程序,并且我设法创建了一个带有渐变颜色的边框。但是,我正在尝试通过添加发光效果和阴影来增强边框的外观。这是我到目前为止拥有的代码片段:
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
}
}
在 GradientBorderView 类中,我使用 gradientCGColors 中定义的颜色创建一个渐变,并将其应用于边框。我还尝试在 addNeonEffect() 函数中添加发光效果,方法是设置一个带有白色和大模糊半径的阴影。
我的目标是使渐变边框具有发光效果,并带有很多阴影。如果是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;
}
但是,当前的解决方案似乎没有提供预期的结果。如果有人能指导我如何达到预期的效果,我将不胜感激。谢谢!
答: 暂无答案
评论