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

SwiftUI圆形进度Gauge尺寸过大,如何调整其大小?

如何缩小SwiftUI圆形Gauge组件的尺寸?

我创建了一个中间带有停止按钮的圆形进度Gauge组件用于进度展示,但该圆形尺寸过大,无法缩小,请问如何调整这个圆形Gauge的大小?

代码:

import SwiftUI

struct DownloadProgressGauge: View {
    var body: some View {
        Gauge(value: 100, in: 0...200) {
            Image(systemName: "gauge.medium").resizable().frame(width: 30, height: 30.0)
        } currentValueLabel: {
            Image(systemName: "stop.fill").font(.caption).bold()
                .foregroundStyle(Color.systemBlue)
                .minimumScaleFactor(0.33)
        }
        .gaugeStyle(.accessoryCircularCapacity)
        .tint(Color.systemBlue)
        .frame(width: 30, height: 30)
    }
}

当前运行效果:
当前圆形Gauge尺寸过大效果

期望效果:
期望的小尺寸圆形Gauge效果


解决方案

问题根源是.accessoryCircularCapacity系统样式存在固定最小尺寸限制,直接设置frame无法突破该限制,可通过以下两种方式解决:

方法1:使用scaleEffect缩放组件

通过比例缩放整个Gauge,同时调整内部元素尺寸适配:

import SwiftUI

struct DownloadProgressGauge: View {
    var body: some View {
        Gauge(value: 100, in: 0...200) {
            Image(systemName: "gauge.medium")
        } currentValueLabel: {
            Image(systemName: "stop.fill")
                .font(.system(size: 12))
                .bold()
                .foregroundStyle(Color.systemBlue)
        }
        .gaugeStyle(.accessoryCircularCapacity)
        .tint(Color.systemBlue)
        .scaleEffect(0.6) // 按需调整缩放比例
        .frame(width: 30, height: 30)
    }
}

方法2:自定义Gauge样式

完全自定义圆形进度样式,摆脱系统样式的尺寸约束,实现精准控制:

import SwiftUI

struct CustomCircularGaugeStyle: GaugeStyle {
    func makeBody(configuration: Configuration) -> some View {
        let progress = configuration.value / (configuration.maxValue ?? 1)
        ZStack {
            // 背景圆环
            Circle()
                .stroke(Color.gray.opacity(0.3), lineWidth: 2)
            // 进度圆环
            Circle()
                .trim(from: 0, to: progress)
                .stroke(Color.systemBlue, lineWidth: 2)
                .rotationEffect(.degrees(-90))
            // 中间停止按钮
            configuration.currentValueLabel
        }
        .frame(width: 30, height: 30)
    }
}

struct DownloadProgressGauge: View {
    var body: some View {
        Gauge(value: 100, in: 0...200) {
            EmptyView()
        } currentValueLabel: {
            Image(systemName: "stop.fill")
                .font(.system(size: 12))
                .bold()
                .foregroundStyle(Color.systemBlue)
        }
        .gaugeStyle(CustomCircularGaugeStyle())
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:35:09