首页 > 解决方案 > 两条路径或一条路径与一个点的交集永远不会返回 true

问题描述

我遇到了这个这个问题,都是关于 Android 中的检测交叉点的。好吧,我无法让它们与最终代码一起工作,所以我做了一个例子,其中 2 行肯定相交。在那种情况下甚至没有运气。我制作了一个示例代码,其中包含两条直线路径、适合它们的区域以及一个绝对穿过它的点。完全倒霉。

var theyCross = false
val intersectionPath = Path()

val clipArea = Region(0, 0, 100, 100)
val path1 = Path()
path1.moveTo(50f, 0f)
path1.lineTo(50f, 100f)

val path2 = Path()
path2.moveTo(0f, 50f)
path2.lineTo(100f, 50f)

val newRegion1 = Region()
newRegion1.setPath(path1, clipArea)

val newRegion2 = Region()
newRegion2.setPath(path2, clipArea)

if(
    !newRegion1.quickReject(newRegion2) && 
    newRegion1.op(newRegion2, Region.Op.INTERSECT)
) {
    // lines should cross!
    theyCross = true
}

if (intersectionPath.op(path1, path2, Path.Op.INTERSECT)) {
    if (!intersectionPath.isEmpty) {
        // lines should cross!
        theyCross = true
    }
}

if (newRegion1.contains(50, 50)) {
    // lines should cross!
    theyCross = true
}

if (newRegion1.quickContains(49, 49, 51, 51)) {
    // lines should cross!
    theyCross = true
}

在此示例中,我没有使用 a Canvas,但在我的原始代码中,我使用了,并且每个路径都由 a Paintwith组成strokeWidth。没运气。你们中有人遇到过这种情况吗?

标签: androidkotlinandroid-canvas

解决方案


它仅在路径是表面而不是线时才有效,例如:

val clipArea = Region(0, 0, 100, 100)
val path1 = Path()
path1.moveTo(50f, 0f)
path1.lineTo(50f, 100f)
path1.lineTo(51f, 100f)
path1.lineTo(51f, 0f)
path1.close()

val path2 = Path()
path2.moveTo(0f, 50f)
path2.lineTo(100f, 50f)
path2.lineTo(100f, 51f)
path2.lineTo(0f, 51f)
path2.close()

顺便说一下(忽略的)返回值newRegion1.setPath(path1, clipArea)现在是 true(非空)而不是 false


推荐阅读