SwiftUI 2.Image介绍和使用
SwiftUI 的 Image
是用于显示图片的核心组件,支持本地图片、系统图标(SF Symbols)、网络图片等。以下是 Image
的详细介绍和使用示例:
一、基础用法
1. 加载本地图片
Image("logo") // 加载 Assets.xcassets 中的图片
2. 使用系统图标(SF Symbols)
Image(systemName: "heart.fill") // SF Symbols 图标.font(.system(size: 30)) // 调整大小.foregroundColor(.red) // 修改颜色
3. 调整图片尺寸和缩放模式
Image("landscape").resizable() // 允许调整尺寸.scaledToFit() // 保持比例填充(常用模式:.fit, .fill, .aspectFit, .aspectFill).frame(width: 200, height: 200)
4. 颜色和渲染模式
Image(systemName: "cloud").renderingMode(.template) // 允许修改颜色(默认行为).foregroundColor(.blue)
二、高级功能
1. 异步加载网络图片(iOS 15+)
AsyncImage(url: URL(string: "https://example.com/image.jpg")) { phase inif let image = phase.image {image.resizable() // 加载成功} else if phase.error != nil {Text("加载失败") // 错误处理} else {ProgressView() // 加载中显示进度}
}
.frame(width: 200, height: 200)
2. 叠加文字或视图
Image("photo").resizable().aspectRatio(contentMode: .fit).overlay(Text("风景").foregroundColor(.white).padding(4).background(Color.black.opacity(0.5)),alignment: .bottomLeading)
3. 图片裁剪与蒙版
// 圆形裁剪
Image("avatar").resizable().aspectRatio(contentMode: .fill).frame(width: 100, height: 100).clipShape(Circle()) // 圆形蒙版(也可用 RoundedRectangle、Capsule 等)// 自定义蒙版
Image("pattern").mask(LinearGradient(colors: [.black, .clear], startPoint: .top, endPoint: .bottom))
三、自定义样式
1. 添加边框和阴影
Image(systemName: "star.fill").padding().background(Color.yellow).clipShape(Circle()).shadow(color: .gray, radius: 5, x: 2, y: 2)
2. 旋转与动画
@State private var rotate = falseImage(systemName: "arrow.right.circle").rotationEffect(.degrees(rotate ? 90 : 0)).animation(.easeInOut(duration: 1), value: rotate).onTapGesture {rotate.toggle()}
四、与其他组件结合
1. 在列表中使用
List {HStack {Image(systemName: "person.circle")Text("用户资料")}
}
2. 作为按钮图标
Button {// 点击动作
} label: {HStack {Image(systemName: "square.and.arrow.up")Text("分享")}
}
五、常见问题
-
图片不显示:
- 检查图片名称是否与 Assets.xcassets 中的完全一致(区分大小写)
- 确保图片已添加到项目 Target
-
处理不同尺寸图片:
- 提供
@1x
,@2x
,@3x
图片以适配不同设备
- 提供
-
性能优化:
- 大图建议压缩或使用缩略图
- 频繁使用的图片可缓存(如
Kingfisher
第三方库)
-
深色模式适配:
Image("logo").colorInvert() // 反转颜色适配深色背景
六、完整示例
struct ContentView: View {@State private var isRotating = falsevar body: some View {VStack(spacing: 20) {// 本地图片Image("swift-logo").resizable().scaledToFit().frame(height: 100)// 动态旋转的 SF SymbolImage(systemName: "gear").font(.system(size: 40)).rotationEffect(.degrees(isRotating ? 360 : 0)).animation(.linear(duration: 2).repeatForever(autoreverses: false), value: isRotating).onAppear { isRotating = true }// 带蒙版的网络图片AsyncImage(url: URL(string: "https://picsum.photos/200")) { phase inif let image = phase.image {image.resizable().aspectRatio(contentMode: .fill).frame(width: 150, height: 150).clipShape(RoundedRectangle(cornerRadius: 20))}}}.padding()}
}
通过灵活使用这些功能,可以实现从简单图标到复杂图片布局的多样化需求。