【问题标题】:Is it possible to use UIKit extensions in SwiftUI?是否可以在 SwiftUI 中使用 UIKit 扩展?
【发布时间】:2021-10-16 03:39:10
【问题描述】:

我有一个不错的 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
  }
}

【问题讨论】:

    标签: ios swift swiftui uiimage


    【解决方案1】:

    您可以像平常一样创建您的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))
            }
        }
    }
    

    【讨论】:

    • 看来问题是我无法像通常那样创建我的 UIImage。即使在共享目标成员身份后,我也无法访问扩展功能
    • @NoahIarrobino 我在我的答案中添加了一个工作示例。你应该使用UIImage.circularImage(...)。它是静态的(不是UIImage 实例上的方法)。
    • 是的,但我仍然收到Type 'UIImage' has no member 'circularImage'
    • @NoahIarrobino 如果在单独的模块中,您需要将其标记为public
    • 扩展是公开的,仍然报错
    猜你喜欢
    • 2020-04-19
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2020-12-22
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多