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

iOS SwiftUI如何实现右上角渐变模糊三角效果?

SwiftUI右上角渐变模糊三角的优化实现方案

核心优化思路

别靠超大半径模糊硬凑效果,而是通过精准路径裁剪+渐变透明度控制+可控模糊+混合分组来匹配原型,既能保留三角的柔和边缘,又不会让形状完全失控。

具体实现代码

struct ContentView: View {
    var body: some View {
        ZStack {
            // 主内容背景(替换成你的实际视图)
            Color.white
                .ignoresSafeArea()
            
            // 右上角渐变三角
            Triangle()
                .fill(
                    LinearGradient(
                        colors: [.pink.opacity(0.6), .yellow.opacity(0.4)],
                        startPoint: .top,
                        endPoint: .bottomTrailing
                    )
                )
                .frame(width: 300, height: 300)
                .blur(radius: 60) // 比100小的半径更可控,避免过度模糊
                .compositingGroup() // 确保模糊只作用于三角本身,不扩散到其他视图
                .offset(x: 120, y: -120) // 调整偏移让三角顶点刚好对齐屏幕右上角
                .allowsHitTesting(false) // 不干扰下层视图的交互
        }
    }
}

// 修正后的三角Shape(确保是右上角向外延伸的形态)
struct Triangle: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        // 路径:右上角顶点 → 左下角 → 右下角 → 回到顶点
        path.move(to: CGPoint(x: rect.maxX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.closeSubpath()
        return path
    }
}

关键优化点说明

  • 修正三角路径:之前的Shape可能路径方向不对,导致渐变和模糊效果错位,上面的路径是标准的右上角向外的三角形态
  • 降低模糊半径:60左右的半径既能保证边缘柔和,又不会让三角形状完全消失
  • 渐变加透明度:给粉黄两色添加opacity,让模糊后的效果更通透,贴合原型的柔和感
  • compositingGroup():避免模糊效果扩散到周围视图,确保只作用于三角本身

进阶适配(如果原型是径向渐变)

如果你的原型是中心亮、边缘渐暗的径向渐变,替换LinearGradient为RadialGradient即可:

RadialGradient(
    gradient: Gradient(colors: [.pink.opacity(0.7), .yellow.opacity(0.3), .clear]),
    center: .topTrailing,
    startRadius: 0,
    endRadius: 250
)

替代方案:背景层裁剪融合

如果需要三角和背景更自然的融合,可以把三角放在背景层配合裁剪:

Color.white
    .ignoresSafeArea()
    .background(
        Triangle()
            .fill(LinearGradient(colors: [.pink, .yellow], startPoint: .top, endPoint: .bottomTrailing))
            .frame(width: 400, height: 400)
            .blur(radius: 80)
            .offset(x: 150, y: -150)
    )
    .clipped()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:05:09