本文介绍了使用Swift,如何确定坐标有序对(x,y)是否在n个有序对的范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift中是否有某种数学函数(或者可能有多个函数可以协同工作),在这里我可以创建一组有序对坐标,然后传入一个有序对坐标以获得bool true/是否是否在集合的范围内是错误的?

Is there a math function of some kind in Swift (or maybe multiple functions that work together), where I can create sets of ordered pair coordinates, and then pass in a single ordered pair coordinate to get a bool true/false of whether it's within the bounds of the set?

我不是最擅长数学的人,所以我希望有人(并且知道如何在Swift中解决此问题)可以在这里为我提供帮助.

I'm not the greatest at math, so I'm hoping someone who is (and understands how to solve this problem in Swift) can help me out here.

示例数据:

我在某人位于纬度的地方有一个坐标.假设(28.3797770, -81.5431893).

I have a coordinate where someone is located in lat-long. Let's say (28.3797770, -81.5431893).

我也有一组对应于一个区域的坐标.它可以是3面或更高.在此示例的屏幕截图中,它是7个坐标.

I also have a set of coordinates that corresponds to an area. It could be 3-sided or higher. In this example with the screenshot, it's 7 coordinates.

latitude, longitude

(28.3795930, -81.5433286)
(28.3797771, -81.5431891)
(28.3797098, -81.5430725)
(28.3796355, -81.5431288)
(28.3794715, -81.5428780)
(28.3793546, -81.5429665)
(28.3795859, -81.5433219)

推荐答案

您可以使用CoreGraphics CGPath和CGPath.contains函数来测试点是否在多边形内.

You can use CoreGraphics CGPath, and the CGPath.contains function to test if a point is inside a polygon.

//: Playground - test if a point is inside polygon

import UIKit
import CoreGraphics

let points = [CGPoint(x: 28.3795930, y: -81.5433286),
              CGPoint(x: 28.3797771, y: -81.5431891),
              CGPoint(x: 28.3797098, y: -81.5430725),
              CGPoint(x: 28.3796355, y: -81.5431288),
              CGPoint(x: 28.3794715, y: -81.5428780),
              CGPoint(x: 28.3793546, y: -81.5429665),
              CGPoint(x: 28.3795859, y: -81.5433219)]

// Build a closed path from points representing the ordered edges of a polygon
func closedPath(points: [CGPoint]) -> CGPath {
    let path = CGMutablePath()
    path.addLines(between: points)
    path.closeSubpath()
    return path
}

let path = closedPath(points: points)
let pointOutside = CGPoint(x: 28.37965, y: -81.5431)
let pointInside = CGPoint(x: 28.3796, y: -81.5431893)

path.contains(pointOutside) // Prints false
path.contains(pointInside)  // Prints true

如果您要针对单个点测试许多区域,则可能需要研究使用数据结构进行空间索引,例如四叉树或k-d树.

If you have many areas that you want to test against a single point, you might want to look into using a data structure for spatial indexing, such as a quadtree, or k-d tree.

这篇关于使用Swift,如何确定坐标有序对(x,y)是否在n个有序对的范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:31