如果我正确理解了你的问题,现在你想在图像中找到由给定点构建的所有线上的所有像素。
由于我现在正在手机上打字,所以不是很确定,但我认为你可以这样做:
// Expects givenPoints in pixel coordinates for positions to draw lines between
public List<Vector2Int> CalculateLinePixels(List<Vector2Int> givenPoints)
{
var output = new List<Vector2Int>();
// Already add the first point once
output.Add(givenPoints[0]);
// start with the second point and calculate the line points back
// between the current and the point before
for (var i = 1; i < givenPoints.Count; i++)
{
var startPoint = givenPoints[i - 1];
var endPoint = givenPoints[i];
// get the difference between them in pixels
var dif = endPoint - startPoint;
// Get the pixel step in Y per pixel step on X
var step = dif.y / (float)dif.x;
// go through all the pixels on the X axis between both points
// excluding the first as these should already match the
// startPoint (== last endPoint)
//
// Note that for now this assumes that the line goes always strict from left to right
// -> no forth and back drawing, no vertical drawing
for (var x = 1; x < dif.x; x++)
{
// every step in X add one step in Y starting from the first points Y
var y = Mathf.RoundToInt(step * x);
// Add the new line point
output.Add(startPoint + new Vector2Int(x, y));
}
}
return output;
}
如代码中所述:
请注意,这假定该行始终严格从左到右。 => 不要来回画,不要水平画。
对于这些情况,您可以添加一些额外的检查,例如if(dif.x < 0)
,然后您需要在另一个方向上进行迭代for (var x = -1; x > dif.x ; x--)
。如果是if(dif.x == 0)
,您可能更想只画一条水平线到下一个点并填充所有上面/下面。
为了获得更好的结果,您可能需要研究线绘制算法并实现一种不同的方式来获取和以不同的方式填充像素。