问题在于 lerp 百分比(例如,在您的可视化中,从高/低或“红色”到“黑色”)只是点到中心距离的函数,除以一个常数(发生这种情况是任何点到中心的最大距离)。这就是为什么它看起来是圆形的。
例如,多边形左侧的最中心点可能距离中心 300 像素,而右侧的最中心点可能距离中心 5 像素。两者都需要是红色的,但是基于0 distance from center = red 不会是红色的,并且基于min distance from center = red 只会在右侧有红色。
相关的最小和最大距离会根据点的位置而变化
另一种方法是针对每个点:找到最近的白色像素,然后找到最近的绿色像素(或者,与绿色/白色相邻的最近的阴影像素,例如here)。然后,根据这两点与当前点之间的距离比较来选择您的红度。
因此,您可以这样做(伪 C#):
foreach pixel p in shadow_region {
// technically, closest shadow pixel which is adjacent to x Pixel:
float closestGreen_distance = +inf;
float closestWhite_distance = +inf;
// Possibly: find all shadow-adjacent pixels prior to the outer loop
// and cache them. Then, you only have to loop through those pixels.
foreach pixel p2 in shadow {
float p2Dist = (p-p2).magnitude;
if (p2 is adjacent to green) {
if (p2Dist < closestGreen_distance) {
closestGreen_distance = p2Dist;
}
}
if (p2 is adjacent to white) {
if (p2Dist < closestWhite_distance) {
closestWhite_distance = p2Dist;
}
}
}
float d = 1f - closestWhite_distance / (closestWhite_distance + closestGreen_distance)
}
使用您在 cmets 中发布的代码,可能如下所示:
foreach (Point p in value)
{
float minOuterDistance = outerPoints.Min(p2 => (p - p2).magnitude);
float minInnerDistance = innerPoints.Min(p2 => (p - p2).magnitude);
float d = 1f - minInnerDistance / (minInnerDistance + minOuterDistance);
Color32? colorValue = func?.Invoke(p.x, p.y, d);
if (colorValue.HasValue)
target[F.P(p.x, p.y, width, height)] = colorValue.Value;
}
选择上述部分作为解决方案。以下部分,作为另一种选择提到,结果证明是不必要的。
如果您无法确定阴影像素是否与白色/绿色相邻,这里有一个替代方法,只需要计算粉红色(原始)轮廓中每个顶点的法线。
通过转到每个粉红色顶点并按照其法线向外创建外部“黄色”顶点。通过转到每个粉红色顶点并按照其法线向内创建内部“蓝色”顶点。
然后,当循环遍历阴影中的每个像素时,循环遍历黄色顶点以获得“最接近绿色”并通过蓝色获得“最接近白色”。
问题在于,由于您的形状不是完全凸出的,因此这些投影的蓝色和黄色轮廓在某些地方可能是由内向外的,因此您需要以某种方式处理它。我无法确定处理该问题的确切方法,但这是我目前所拥有的:
一个步骤是忽略任何具有指向当前阴影像素的外部法线的蓝色/黄色。
但是,如果当前像素位于黄色/蓝色形状由内向外的点内,我不确定如何继续。可能会忽略比应有的距离最近的粉红色顶点更近的蓝色/黄色顶点。
非常粗略的伪代码:
list yellow_vertex_list = new list
list blue_vertex_list = new list
foreach pink vertex p:
given float dist;
vertex yellowvertex = new vertex(p+normal*dist)
vertex bluevertex = new vertex(p-normal*dist)
yellow_vertex_list.add(yellowvertex)
blue_vertex_list.add(bluevertex)
create shadow
for each pixel p in shadow:
foreach vertex v in blue_vertex_list
if v.normal points towards v: break;
if v is the wrong side of inside-out region: break;
if v is closest so far:
closest_blue = v
closest_blue_dist = (v-p).magnitude
foreach vertex v in yellow_vertex_list
if v.normal points towards v break;
if v is the wrong side of inside-out region: break;
if v is closest so far:
closest_yellow = v
closest_yellow_dist = (v-p).magnitude
float d = 1f - closest_blue_dist / (closest_blue_dist + closest_yellow_dist)