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

SwiftUI中如何为图形绘制对应百分比的部分描边?

SwiftUI 实现按百分比显示的矩形描边组件

要实现按百分比显示部分描边的效果,你可以通过trim修饰符配合stroke来控制边框的显示长度,替代原来的两层填充背景方案。以下是修改后的完整代码:

VStack {
    Text(dayAbbreviation)
        .foregroundColor(Color("dark_grey"))
        .font(.title)
    
    Text(String(day))
        .padding(.horizontal)
        .font(.largeTitle)
    
    Text("\(percentageCompleted)%")
        .font(.footnote)
        .foregroundColor(Color("dark_grey"))
        .bold()
        .padding(.bottom, 2)
}
.background {
    Rectangle()
        .fill(.white)
        .cornerRadius(3.0)
}
.padding(8)
.background {
    // 按百分比显示的描边背景
    Rectangle()
        .trim(from: 0, to: percentageCompleted / 100)
        .stroke(.blue, lineWidth: 8) // lineWidth和外层padding保持一致
        .cornerRadius(3.0)
        .rotationEffect(.degrees(-90)) // 调整起始方向,默认从右侧开始,旋转后从底部开始
}

关键说明:

  • trim修饰符:通过from和to参数控制图形显示的比例,percentageCompleted / 100将百分比转换为0-1之间的数值,比如50%对应to: 0.5,仅显示一半边框。
  • rotationEffect:默认trim起始点在矩形右侧,添加旋转可调整描边起始位置(比如从底部向上绘制),不需要可直接删除该行。
  • lineWidth与padding匹配:外层padding(8)和描边lineWidth(8)保持一致,确保描边刚好作为组件边框显示。
  • 修正颜色方法:SwiftUI中正确的文本颜色设置为foregroundColor,替换原代码中的foregroundStyleColor避免报错。

如果需要更精细的视觉控制,可自定义StrokeStyle优化描边端点和转角:

.stroke(
    .blue,
    style: StrokeStyle(
        lineWidth: 8,
        lineCap: .round,
        lineJoin: .round
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:10:20