swiftuimapkitstrokemkpolygon

Mapkit SwiftUI MKPolygon border color


I am writing an app for iOS 17 to check out the new and improved MapKit support in SwiftUI. So far, I have managed to draw MKPolygons and give them Polygons a Fill color, by using:

    MapPolygon(polygon)
       .foregroundStyle(properties.type.color.opacity(0.2))

However, I would (also) like to give the MKPolygon a border color. In MapKit in UIKit, this was done by using the 'strokeColor' like so:

    let renderer = MKPolygonRenderer(overlay: overlay)
    renderer.lineWidth = 1
    renderer.fillColor = properties.type.color.withAlphaComponent(0.15)
    renderer.strokeColor = properties.type.color.withAlphaComponent(0.35)
    return renderer

I cannot find a way to give the MKPolygon a border(stroke) and a fill color in SwiftUI.


Solution

  • There are multiple overloads of stroke that you can use. You can pass in any ShapeStyle, a subset of which are Colors. Other ShapeStyles include gradients (.linearGradient(...)) and materials (.regularMaterial).

    MapPolygon(polygon)
        // assuming properties.type.color is of type Color
        .stroke(properties.type.color.opacity(0.35))