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)computes100 / -40as-2instead of the correct-2.5, throwing off all X coordinate calculations. - Line equation ignores the starting point: The formula
x = y/slopeassumes 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 aty=99and 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
相关产品推荐
相关产品推荐

