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

SwiftUI中自定义Shape图形无法正常填充颜色的问题求助

问题根因

  • stroke(_:lineWidth:) 是 Shape 类型的专属方法,调用后会返回一个描边完成的 View 实例,不再属于 Shape 类型。而 fill(_:) 仅对 Shape 类型生效,对普通 View 调用不会产生任何填充效果,你代码中的调用顺序错误导致填充失效。
  • 你需要的「同时对Shape实现填充+描边」的效果,不能直接链式调用 fill 和 stroke,需要通过叠加视图的方式实现。

修正方案

把ShapeView中Triangle的相关代码替换为以下写法即可:

// 写法1:用overlay叠加描边层
Triangle()
    .fill(fillColor)
    .overlay(
        Triangle()
            .stroke(lineWidth: lineWidth)
    )

// 写法2:直接在ZStack里加两层Triangle分别处理填充和描边
ZStack {
  Square()
    .stroke(lineWidth:lineWidth)
  Triangle()
    .fill(fillColor)
  Triangle()
    .stroke(lineWidth:lineWidth)
}
.frame(width: 200, height: 200, alignment: .center)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:03