#3 Creating Shapes in SwiftUI

示例程序

swift 复制代码
struct ShapesBootcamp: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 4)
            .stroke(
                Color.purple,
                style: StrokeStyle(lineWidth: 4, dash: [10, 5])
            )
            .frame(width: 200, height: 100)
    }
}

形状类型

类型 初始化 几何描述
Circle() 无参 外接最小圆
Ellipse() 无参 外接椭圆
Capsule(style:) .circular / .continuous 两端半圆
Rectangle() 无参 无圆角
RoundedRectangle(cornerRadius:style:) 半径 + 风格 四角等半径

所有形状默认撑满父视图提案尺寸;使用 .frame() 可强制固定宽高。

视觉修饰符

修饰符 功能 示例 备注
.fill(_:) 内部填充 .fill(Color.blue) 支持纯色、渐变
.stroke(_:lineWidth:) 等宽描边 .stroke(.red, lineWidth: 2) 默认线帽 butt
.stroke(_:style:) 高级描边 .stroke(.orange, style: StrokeStyle(...)) 虚线、线帽、线连接
.trim(from:to:) 路径裁剪 .trim(from: 0.2, to: 0.8) 0--1 比例
.frame(width:height:alignment:) 固定尺寸 .frame(200, 100) 形状无固有尺寸
.scale(_:anchor:) 缩放 .scale(1.2) 锚点默认 center
.rotation(_:anchor:) 旋转 .rotation(.degrees(45)) 同上
.offset(x:y:) 平移 .offset(x: 10) 仅视觉偏移
.opacity(_:) 透明度 .opacity(0.5) 0--1
.blendMode(_:) 混合模式 .blendMode(.multiply) 需同级 ZStack
.mask(_:) 遮罩 .mask(Circle()) 支持任意 View
.shadow(color:radius:x:y:) 阴影 .shadow(.black, 4, x: 2, y: 2) 先阴影后形状
.accessibilityHidden(true) 隐藏朗读 见上 纯装饰时推荐

任务速查表

需求 片段
圆角按钮背景 RoundedRectangle(cornerRadius: 12).fill(.accent)
环形进度 Circle().trim(from: 0, to: progress).stroke(.blue, lineWidth: 4)
虚线边框 Rectangle().stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
胶囊标签 Capsule().fill(Color.gray.opacity(0.2))

性能与可访问性

  1. 矢量路径自动适配 @2x/@3x,无位图失真。
  2. 支持动态颜色与「降低透明度」辅助选项。
  3. 动画复杂时启用 .drawingGroup() 以 Metal 合成,降低 CPU 负担。
  4. 纯装饰形状请附加 .accessibilityHidden(true),避免 VoiceOver 读出「图像」。
相关推荐
AGoodrMe1 天前
swift基础之async/await
前端·ios
hhb_6181 天前
Swift核心技术难点与实战案例解析
开发语言·ios·swift
人月神话-Lee1 天前
【图像处理】饱和度——颜色的浓淡与灰度化
图像处理·人工智能·ios·ai编程·swift
人月神话-Lee2 天前
【图像处理】卷积原理与卷积核——图像处理的核心引擎
图像处理·深度学习·ios·ai编程·swift
2501_915106322 天前
深入解析无源码iOS加固原理与方案,保护应用安全
android·安全·ios·小程序·uni-app·cocoa·iphone
Daniel_Coder2 天前
iOS Widget 开发-15:Widget 性能优化指南
ios·swift·widget·widgetcenter
库奇噜啦呼2 天前
【iOS】源码学习-dyld加载
学习·ios·cocoa
Daniel_Coder2 天前
iOS Widget 开发-16:Widget 网络数据加载策略
ios·swift·widget·widgetcenter
美狐美颜SDK开放平台2 天前
美颜SDK开发详解:如何优化美颜SDK在低端安卓机上的性能?
android·ios·音视频·直播美颜sdk·视频美颜sdk
Kurisu5752 天前
FilzaCracked_4.0.0_TS.ipa2026最新官方正版免费下载 一键转存 永久更新 (看到速转存 资源随时走丢)手机版通用
ios·智能手机·电脑·巨魔