You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求SwiftUI实现带侧边渐变阴影按钮的方案(已实现渐变边框)

SwiftUI 实现侧边渐变阴影按钮方案

核心思路

利用ZStack将渐变阴影层叠加在带渐变边框的按钮主体后方,通过偏移、透明度和渐变方向控制,模拟出侧边的渐变阴影效果。

完整实现代码

import SwiftUI

struct GradientShadowButton: View {
    let title: String
    let action: () -> Void
    
    // 渐变颜色配置(可根据需求调整)
    private let borderGradient = LinearGradient(
        colors: [Color.purple, Color.blue],
        startPoint: .leading,
        endPoint: .trailing
    )
    
    private let shadowGradient = LinearGradient(
        colors: [Color.purple.opacity(0.3), Color.blue.opacity(0.1)],
        startPoint: .leading,
        endPoint: .trailing
    )
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.headline)
                .foregroundColor(.white)
                .padding(.vertical, 12)
                .padding(.horizontal, 32)
                .background(Color.black)
                .clipShape(RoundedRectangle(cornerRadius: 8))
                // 已完成的渐变边框
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(borderGradient, lineWidth: 2)
                )
        }
        // 添加侧边渐变阴影
        .background(
            shadowGradient
                .clipShape(RoundedRectangle(cornerRadius: 8))
                // 向右下方偏移,模拟侧边阴影
                .offset(x: 4, y: 4)
                // 限制阴影仅显示在按钮右侧和下方区域(可选,根据效果调整)
                .mask(
                    RoundedRectangle(cornerRadius: 8)
                        .fill(LinearGradient(
                            colors: [.clear, .black],
                            startPoint: .leading,
                            endPoint: .trailing
                        ))
                )
        )
        .buttonStyle(PlainButtonStyle())
    }
}

// 预览
struct GradientShadowButton_Previews: PreviewProvider {
    static var previews: some View {
        GradientShadowButton(title: "渐变阴影按钮") {}
            .padding()
            .background(Color.gray.opacity(0.1))
    }
}

关键细节调整

  • 阴影偏移:修改offset(x: 4, y: 4)的数值可以控制阴影的位置和大小,数值越大阴影越明显
  • 渐变透明度:调整shadowGradient中颜色的opacity参数,控制阴影的深浅
  • 阴影范围:如果需要更精准的侧边阴影,可调整mask里的渐变方向和颜色,或者直接用Rectangle裁剪出右侧区域
  • 边框样式:如果你的原有渐变边框有特殊样式,直接替换borderGradient的配置即可

内容的提问来源于stack exchange,提问作者Jecky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:43:24