How to draw a line using y = mx +b in java?

雨燕双飞 提交于 2019-12-20 07:28:20

问题


So I have a program that solves a system of linear equations, but that is not relevant. So what happens is that my program pass two linear equations in the form of: y = mx +b. I do not know how I would graph this using Graphics2D, I am having some trouble figuring it out. Right now I have no idea so I have no code that I could show you, but I can tell you that:

  • That my program correctly converts Ax + By = C into y = mx + B
  • That it would be helpful to show an example in some code possibly using the drawLine() method

回答1:


When you draw a line in code, you need to draw from point A to point B. (a line segment)

Pick a point A to start the line from, then draw from A to (A.X + dx, A.Y + m * dx), where dx is the desired width of the line.

For example, you may want A to be one corner of your area, and dx to be the width of the area.




回答2:


You also need to consider how to map from physical (x, y) coordinates to screen (u, v) coordinates.

Transforming from Ax + By = C is mere high school algebra:

  1. Subtract Ax from both sides: By = C - Ax
  2. Divide both sides by B: y = (C/B) - (A/B)x
  3. By inspection, m = -(A/B) and b = (C/B). Obviously, B != 0.



回答3:


drawLine draws a line between two points. So all you need to do is get two points from your equation and pass them into drawLine.

Example:

x1 = 0
x2 = 10
y1 = m*x1 + b
y2 = m*x2 + b;
g2d.drawLine(x1, y1, x2, y2);

Of course this will draw a line segment between the two points. So you need to figure out which segment of the line you are interested in actually drawing and pick you x values accordingly.



来源:https://stackoverflow.com/questions/7410614/how-to-draw-a-line-using-y-mx-b-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!