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

SwiftUI中修改accessoryCircularCapacity样式Gauge的背景与厚度

SwiftUI Gauge:设置透明背景与调整厚度

系统自带的.accessoryCircularCapacity样式无法直接修改背景透明度和圆环厚度,你可以通过自定义GaugeStyle来实现这两个需求:

自定义Gauge样式

创建一个自定义样式类,手动绘制背景环和进度环,同时开放厚度、颜色等参数:

struct CustomCircularCapacityGaugeStyle: GaugeStyle {
    var thickness: CGFloat
    var tintColor: Color
    var backgroundColor: Color
    
    func makeBody(configuration: Configuration) -> some View {
        ZStack {
            // 背景圆环
            Circle()
                .stroke(backgroundColor, lineWidth: thickness)
            
            // 进度圆环(从顶部开始旋转)
            Circle()
                .trim(from: 0, to: configuration.value)
                .stroke(tintColor, style: StrokeStyle(lineWidth: thickness, lineCap: .round))
                .rotationEffect(.degrees(-90))
        }
        .frame(width: 60, height: 60) // 可根据需求调整整体尺寸
    }
}

// 扩展GaugeStyle,简化调用方式
extension GaugeStyle where Self == CustomCircularCapacityGaugeStyle {
    static func customCircularCapacity(
        thickness: CGFloat = 8,
        tintColor: Color = .green,
        backgroundColor: Color = .clear
    ) -> CustomCircularCapacityGaugeStyle {
        CustomCircularCapacityGaugeStyle(
            thickness: thickness,
            tintColor: tintColor,
            backgroundColor: backgroundColor
        )
    }
}

使用示例

在视图中调用自定义样式,实现多个透明背景Gauge堆叠,同时调整各自的厚度:

struct ContentView: View {
    var body: some View {
        ZStack {
            // 外层绿色厚环
            Gauge(value: 42, in: 0 ... 100) {
                Text("")
            }
            .gaugeStyle(.customCircularCapacity(thickness: 12, tintColor: .green))
            
            // 内层蓝色薄环
            Gauge(value: 75, in: 0 ... 100) {
                Text("")
            }
            .gaugeStyle(.customCircularCapacity(thickness: 6, tintColor: .blue))
        }
    }
}

说明

  • 背景环通过backgroundColor参数设置为.clear,让堆叠的Gauge可以互相显示。
  • thickness参数直接控制圆环的线条宽度,按需调整即可。
  • 自定义样式的尺寸可以通过frame修饰符修改,适配不同场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:10:09