Skip to content

使用图像视图(Image)

使用图像视图,让你的 SwiftUI 应用更生动!🖼️ 图像是用户体验的关键,让我们一起探索如何在 SwiftUI 中轻松添加和定制图像。

加载本地图像资源

首先,你需要将图像添加到你的项目资源中。你可以将图像拖放到 Xcode 项目导航器的 Assets.xcassets 文件夹中。确保图像格式是 SwiftUI 支持的,例如 PNG 或 JPEG。

swift
Image("myImage")
    .resizable()
    .aspectRatio(contentMode: .fit)
  • Image("myImage"):创建一个图像视图,"myImage" 是你在 Assets.xcassets 中图像的名称。
  • .resizable():允许图像调整大小以适应可用空间。
  • .aspectRatio(contentMode: .fit):保持图像的宽高比,并确保图像完整显示。

使用系统图标

SwiftUI 提供了丰富的系统图标,你可以直接使用它们,无需导入任何资源。这对于添加常见的操作图标非常方便。🚀

swift
Image(systemName: "heart.fill")
    .foregroundColor(.red)
    .font(.system(size: 50))
  • Image(systemName: "heart.fill"):创建一个系统图标,"heart.fill" 是一个填充的心形图标。
  • .foregroundColor(.red):设置图标的颜色为红色。
  • .font(.system(size: 50)):设置图标的大小为 50。

自定义图像视图

你可以使用修饰符来进一步定制图像视图的外观。例如,你可以添加阴影、边框或调整图像的不透明度。✨

swift
Image("myImage")
    .resizable()
    .frame(width: 200, height: 200)
    .clipShape(Circle())
    .overlay(Circle().stroke(Color.white, lineWidth: 4))
    .shadow(radius: 7)
  1. .frame(width: 200, height: 200):设置图像的宽度和高度为 200。
  2. .clipShape(Circle()):将图像裁剪为圆形。
  3. .overlay(Circle().stroke(Color.white, lineWidth: 4)):在图像上添加一个白色边框。
  4. .shadow(radius: 7):为图像添加阴影。

从 URL 加载图像

你还可以从 URL 加载图像。这需要使用 Combine 框架和一些异步操作。这是一个更高级的主题,但非常有用。🌐

swift
import SwiftUI
import Combine

class ImageLoader: ObservableObject {
    @Published var image: UIImage?
    private var cancellable: AnyCancellable?

    init(url: String) {
        loadImage(from: url)
    }

    func loadImage(from url: String) {
        guard let imageURL = URL(string: url) else { return }

        cancellable = URLSession.shared.dataTaskPublisher(for: imageURL)
            .map { UIImage(data: $0.data) }
            .replaceError(with: nil)
            .receive(on: DispatchQueue.main)
            .sink { [weak self] in self?.image = $0 }
    }
}

struct ContentView: View {
    @ObservedObject var imageLoader = ImageLoader(url: "https://example.com/image.jpg")

    var body: some View {
        Image(uiImage: imageLoader.image ?? UIImage(systemName: "photo")!)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 200, height: 200)
    }
}

希望这些示例能帮助你更好地理解如何在 SwiftUI 中使用图像视图。继续探索,你会发现更多有趣的应用!🎉

本站使用 VitePress 制作