You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#基于两点计算斜率绘制直线像素点时坐标偏差问题求助

Fixing Line Drawing Coordinate Calculation in C#

Let's break down what's going wrong with your code and fix it step by step. Your goal is to plot pixels from (40, 0) to (0, 100), but right now the X coordinates are starting at 0 and going negative instead of starting at 40 and decreasing to 0. Here's why, and how to fix it:

Core Issues in Your Code

  • Integer division distorts the slope: In C#, dividing two integers returns an integer result. Your slope calculation (p2.Y - p1.Y)/(p2.X - p1.X) computes 100 / -40 as -2 instead of the correct -2.5, throwing off all X coordinate calculations.
  • Line equation ignores the starting point: The formula x = y/slope assumes the line passes through the origin (0,0), but your line starts at (40, 0). You need to use the point-slope form of the line equation to account for your actual starting point.
  • Loop misses the endpoint: Your loop uses y < p2.Y, which stops at y=99 and never plots the final point (0,100).

Corrected Code

Point p1 = new Point(40, 0);
Point p2 = new Point(0, 100);
// Cast one value to double to force floating-point division
var slope = (double)(p2.Y - p1.Y) / (p2.X - p1.X);
// Include the endpoint by using <= instead of <
for (var y = p1.Y; y <= p2.Y; y++)
{
    // Point-slope formula: y - y1 = slope*(x - x1) → solved for x
    var x = p1.X + (y - p1.Y) / slope;
    // Round to nearest integer for pixel coordinates
    int pixelX = (int)Math.Round(x);
    Console.WriteLine("{0} {1}", pixelX, y);
}

Verification of the Math

  • When y=0 (starting point): x = 40 + (0-0)/-2.5 = 40 → matches your expected starting X.
  • When y=100 (endpoint): x = 40 + (100-0)/-2.5 = 40 - 40 = 0 → hits your target endpoint.
  • For midpoints like y=50: x = 40 + 50/-2.5 = 20 → correctly sits halfway between the two points.

Bonus: Robustness for Edge Cases

If you need to handle horizontal, vertical, or steeper lines later, the slope-based approach might run into issues (like division by zero for vertical lines). For a more reliable solution tailored to pixel drawing, consider implementing Bresenham's Line Algorithm—it avoids floating-point operations entirely and is optimized for custom graphics environments.

内容的提问来源于stack exchange,提问作者TBowman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:47:48