| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- //
- // MapKit+E.swift
- // Pods
- //
- // Created by Groot on 2025/5/14.
- //
- import MapKit
- import Foundation
- extension MKMapView {
- // 按比例 按padding适应annotation
- public func fitsAllPoints(
- points: [MKMapPoint],
- padding: UIEdgeInsets,
- aspectRatio: Double? = nil,
- animated: Bool = true
- ) {
- var zoomRect: MKMapRect = .null
- for point in points {
- let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
- if zoomRect.isNull {
- zoomRect = pointRect
- } else {
- zoomRect = zoomRect.union(pointRect)
- }
- }
- // Calculate the desired size based on the aspect ratio
- let aspectRatio = aspectRatio ?? 1.0
- let width = zoomRect.size.width
- let height = zoomRect.size.height
- let desiredWidth = max(width, height * aspectRatio)
- let desiredHeight = max(height, width / aspectRatio)
- // Calculate the center of the annotations
- let center = MKMapPoint(x: zoomRect.midX, y: zoomRect.midY)
- // Create a new MKMapRect with the desired aspect ratio and centered on the annotations
- let newMapRect = MKMapRect(
- x: center.x - desiredWidth / 2,
- y: center.y - desiredHeight / 2,
- width: desiredWidth,
- height: desiredHeight
- )
- setVisibleMapRect(newMapRect, edgePadding: padding, animated: animated)
- }
- func calculateMapRect(points: [MKMapPoint], padding: UIEdgeInsets = .zero) -> MKMapRect {
- var zoomRect: MKMapRect = .null
- for point in points {
- let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
- if zoomRect.isNull {
- zoomRect = pointRect
- } else {
- zoomRect = zoomRect.union(pointRect)
- }
- }
- return mapRectThatFits(zoomRect, edgePadding: padding)
- }
- func takeSnapShot(option: MKMapSnapshotter.Options, completion: @escaping (MKMapSnapshotter.Snapshot?) -> Void) {
- let shotter = MKMapSnapshotter(options: option)
- shotter.start(with: .global()) { shot, _ in
- completion(shot)
- }
- }
- }
|