是否可以在 SwiftUI 中使用 UIKit 扩展?

Is it possible to use UIKit extensions in SwiftUI?

我有一个很好的 UIImage 扩展,可以使用更少的内存渲染高质量的圆形图像。我想使用此扩展程序或在 SwiftUI 中重新创建它以便我可以使用它。问题是我对 SwiftUI 还很陌生,不确定是否可行。有没有办法使用它?

这是分机:

extension UIImage {
  class func circularImage(from image: UIImage, size: CGSize) -> UIImage? {
      let scale = UIScreen.main.scale
      let circleRect = CGRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale)

      UIGraphicsBeginImageContextWithOptions(circleRect.size, false, scale)

      let circlePath = UIBezierPath(roundedRect: circleRect, cornerRadius: circleRect.size.width/2.0)
      circlePath.addClip()

      image.draw(in: circleRect)

      if let roundImage = UIGraphicsGetImageFromCurrentImageContext() {
          return roundImage
      }

      return nil
  }
}

您可以像往常一样创建 UIImage

然后,只需将其转换为 SwiftUI 图像:

Image(uiImage: image)

不要在视图主体或初始化程序中初始化您的 UIImage,因为这可能非常昂贵 - 而是在 onAppear(perform:).

出现时进行

示例:

struct ContentView: View {
    @State private var circularImage: UIImage?

    var body: some View {
        VStack {
            Text("Hello world!")

            if let circularImage = circularImage {
                Image(uiImage: circularImage)
            }
        }
        .onAppear {
            guard let image: UIImage = UIImage(named: "background") else { return }
            circularImage = UIImage.circularImage(from: image, size: CGSize(width: 100, height: 100))
        }
    }
}