Is it possible to use UIKit extensions in SwiftUI?

Viewed 139

I have a nice UIImage extension that renders circular images in high quality using less memory. I want to either use this extension or re-create it in SwiftUI so I can use it. The problem is I am very new to SwiftUI and am not sure if it is even possible. Is there a way to use this?

Here's the extension:

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
  }
}
1 Answers

You can create your UIImage like normal.

Then, just convert this to a SwiftUI image with:

Image(uiImage: image)

Do not initialize your UIImage in the view body or initializer, as this can be quite expensive - instead do it on appear with onAppear(perform:).

Example:

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))
        }
    }
}
Related