Remove white background on MKAnnotationView

38 Views Asked by At

So I have an annotation that is being created using MKAnnotationView, but I am attempting to utilize SwiftUI to actually created the view instead of UIKit, but I'm having some problems.

So I have the following class which is for the MKAnnotationView:

final class LandmarkAnnotationView2: MKAnnotationView {
    static let ReuseID = "landmarkAnnotation"
    var place: Place?
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func prepareForDisplay() {
        super.prepareForDisplay()
        image = LandmarkPin(
            isBrown: (place?.show ?? false)
        ).takeScreenshot(
            origin: CGPoint(x: 0, y: 0),
            size: CGSize(width: 35, height: 35)
        )
    }
}

This class has two helper extensions, which are these:

extension UIView {
    var renderedImage: UIImage {
        // rect of capure
        let rect = self.bounds
        // create the context of bitmap
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        self.layer.render(in: context)
        // get a image from current context bitmap
        let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return capturedImage
    }
}

extension View {
    func takeScreenshot(origin: CGPoint, size: CGSize) -> UIImage {
        let window = UIWindow(frame: CGRect(origin: origin, size: size))
        let hosting = UIHostingController(rootView: self)
        hosting.view.frame = window.frame
        window.addSubview(hosting.view)
        window.makeKeyAndVisible()
        return hosting.view.renderedImage
    }
}

Now I can create my SwiftUI view called LandmarkPin() with the following code:

struct LandmarkPin: View {
    var isBrown = false
    var body: some View {
        Image("map-pin-full-cluster-1")
            .renderingMode(.template)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 35)
            .clipped()
            .foregroundColor(.blue)
    }
}

The problem that I'm having is that there is a white background attached to the image, no matter what modifiers I pass down, as shown here:

enter image description here

Does anyone know what I might be doing wrong or how I can successfully call a SwiftUI View for a MKAnnotationView, but make the background transparent? The Image is a SVG, which has no background when I output it outside of MKAnnotationView.

0

There are 0 best solutions below