gpt4 book ai didi

swift - 用颜色填充 map 中的区域

转载 作者:行者123 更新时间:2023-11-28 06:30:39 25 4
gpt4 key购买 nike

我一直在用 Swift 3 做一个项目。

我通过在 map 上触摸来选择我的点,然后用一条线将它们链接起来。

我一直在尝试用红色填充这些点之间的区域,但没有成功。我怎样才能完成这个?

我在 map View 中设置了填充颜色,但它不起作用。

到目前为止我有这段代码:

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var map: MKMapView!

var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() //all touched points

override func viewDidLoad() {
super.viewDidLoad()

map.delegate = self

let latitude: CLLocationDegrees = 38.925560
let longitude: CLLocationDegrees = -9.229723
let lanDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: lanDelta, longitudeDelta: lonDelta)
let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: coordinates, span: span)

map.setRegion(region, animated: true)

let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))

uilpgr.minimumPressDuration = 0.5

map.addGestureRecognizer(uilpgr)
}

func longpress(gestureRecognizer: UIGestureRecognizer) {
guard gestureRecognizer.state == .began else { return }

let touchPoint = gestureRecognizer.location(in: self.map)
let coordinate = map.convert(touchPoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()

annotation.coordinate = coordinate
annotation.title = "My Place"
map.addAnnotation(annotation)

// print("longpress activated")
points.append(annotation.coordinate)

let polyline = MKPolyline(coordinates: points, count: points.count)
map.add(polyline)
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.fillColor = UIColor.red
polylineRenderer.lineWidth = 5
return polylineRenderer
}
}

最佳答案

MKPolyLine 将渲染一条线。如果你想要一个填充的多边形,你需要 MKPolyon。如果您同时需要轮廓和填充,请同时使用。

    fileprivate var polygon: MKPolygon? = nil

func addPolygon() {
let polygon = MKPolygon(coordinates: &polygonCoordinates, count: polygonCoordinates.count)
self.polygon = polygon
mapView.add(polygon)
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let _ = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyLine!)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 2
return renderer
} else {
let renderer = MKPolygonRenderer(polygon: polygon)
renderer.fillColor = UIColor.blue.withAlphaComponent(0.25)
return renderer
}
}

关于swift - 用颜色填充 map 中的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40470200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com