iOS - 检查[CGPoint]直线
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS - 检查[CGPoint]直线相关的知识,希望对你有一定的参考价值。
假设我有一个CGPoints
数组,我该如何检查它们是否产生一条直线?
例如,想象一个网格。假设我绘制了网格上的所有点,我如何检查所有点是否为直线水平线,垂直线或对角线?
答案
一种方法是计算你的点的Line of Best Fit,以确定它们是否在一条线上。
func pointsFormALine(_ points: [CGPoint]) -> Bool {
// helper function to test if CGFloat is close enough to zero
// to be considered zero
func isZero(_ f: CGFloat) -> Bool {
let epsilon: CGFloat = 0.00001
return abs(f) < epsilon
}
// variables for computing linear regression
var sumXX: CGFloat = 0 // sum of X^2
var sumXY: CGFloat = 0 // sum of X * Y
var sumX: CGFloat = 0 // sum of X
var sumY: CGFloat = 0 // sum of Y
for point in points {
sumXX += point.x * point.x
sumXY += point.x * point.y
sumX += point.x
sumY += point.y
}
// n is the number of points
let n = CGFloat(points.count)
// compute numerator and denominator of the slope
let num = n * sumXY - sumX * sumY
let den = n * sumXX - sumX * sumX
// is the line vertical or horizontal?
if isZero(num) || isZero(den) {
return true
}
// calculate slope of line
let m = num / den
// calculate the y-intercept
let b = (sumY - m * sumX) / n
print("y = (m)x + (b)")
// check fit by summing the squares of the errors
var error: CGFloat = 0
for point in points {
// apply equation of line y = mx + b to compute predicted y
let predictedY = m * point.x + b
error += pow(predictedY - point.y, 2)
}
return isZero(error)
}
测试:
pointsFormALine([CGPoint(x: 1, y: 2), CGPoint(x: 2, y: 4), CGPoint(x: 5, y: 10)]) // true
pointsFormALine([CGPoint(x: 1, y: 2), CGPoint(x: 1, y: 4), CGPoint(x: 1, y: 10)]) // true
pointsFormALine([CGPoint(x: 1, y: 2), CGPoint(x: 2, y: 2), CGPoint(x: 5, y: 2)]) // true
pointsFormALine([CGPoint(x: 1, y: 2), CGPoint(x: 2, y: 1), CGPoint(x: 2, y: 2)]) // false
以上是关于iOS - 检查[CGPoint]直线的主要内容,如果未能解决你的问题,请参考以下文章
ios - 获取 UIBarButtonItem 的坐标或 CGPoint
pyhton—opencv直线检测(HoughLines)找到最长的一条线