您当然可以根据您想要的任何形状进行测试,而不是针对盒子进行测试。
我最初发布了您可以使用 NSBezierPath,但显然 iPhone 套件上不可用,只能在 Mac 上使用。相反,在 iPhone 上您可以使用 CGPath。
创建一个新的路径,使用CGPathCreateMutable()
它返回一个const CGPath *
(也称为CHPathRef
然后使用CGPathAddRect
或CGPathAddLines
创建我们的路径。
CGPathContainsPoint
将测试您的点是否在形状中。
或者,您可以创建一个客户函数(因为您使用三角形)只进行简单计算以检查您的点是否在三角形形状内。一点数学应该可以解决问题(虽然当你旋转形状时它会稍微复杂一些。我稍微写一下,因为你可以相对于形状的原点旋转触摸点并进行命中检测)
对于三角形:
C
/\
/__\
A B
point of touch is P
使用以下算法,您应该能够找到触摸:
/* first test against a box, for performance */
if( P.y > C.y || P.y < A.y || P.x < A.x || P.X > B.x )
return false; // false if P falls outside "the box"
/* then check if its within the shape */
/* split the triangle into 2 parts, around the axle of point C */
if( P.x < C.x ) // if the x value of point P is on the left of point C
if( P.y > ((C.y -A.y) / (C.x - A.x)) * P.x )
return false; // the point is above the triangle's side AC
else // if the x value of point P is greater than or equal to point C
if( P.y > C.y - ((C.y - B.y) / ( B.x - C.x )) * ( P.x - C.x ) )
return false; // the point is above the triangle's side BC
return true; // the point must be in the triangle, so return true.
以上是干编码,但应该是正确的。
以上仅适用于我绘制的形状中的三角形(其中 Cx 位于 Ax 和 Bx 之间,A 和 B 处于相同高度,但低于 C)。当然,您可以对其进行修改以针对任何形状进行测试,但是,您必须权衡仅使用可用的CGPath
.
如果你不明白,或者它有问题,请告诉我!