我需要创建一个简单的Java程序,通过任意数量的点逐个像素地绘制贝塞尔曲线.此刻,一切似乎都没问题,只是曲线总是在x = 0 y = 0坐标处结束.
截图1
截图2
我需要它在最后一点结束.我的大脑今天工作不太好,所以我正在寻求帮助.
这是我有的:private void drawScene(){
precision = Float.parseFloat(this.jTextField4.getText());
//Clears the screen and draws X and Y lines
g.setColor(Color.white);
g.fillRect(0, 0, pWidth, pHeight);
g.setColor(Color.gray);
g.drawLine(0, offsetY, pWidth, offsetY);
g.drawLine(offsetX, 0, offsetX, pHeight);
//Drawing the points
if(pointCount > 0){
for(int i = 0;i
g.setColor(Color.red);
g.drawString(String.valueOf(i 1), points[i].x offsetX, points[i].y - 6 offsetY);
g.drawOval(points[i].x offsetX, points[i].y - 6 offsetY, 3, 3);
}
}
//Drawing the curve
if(pointCount > 1){
float t = 0;
while(t <= 1){
g.setColor(Color.gray);
this.besierCurvePixel(t);
t = precision;
}
}
}
//Factorial
private static int fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i ) {
fact *= i;
}
return fact;
}
//Bernstein polynomial
private static double bernstein(float t, int n, int i){
return (fact(n) / (fact(i) * fact(n-i))) * Math.pow(1-t, n-i) * Math.pow(t, i);
}
private void besierCurvePixel(float t){
double bPoly[] = new double[pointCount];
for(int i = 0; i < pointCount; i ){
bPoly[i] = bernstein(t, pointCount, i 1);
}
double sumX = 0;
double sumY = 0;
for(int i = 0; i < pointCount; i ){
sumX = bPoly[i] * points[i].x;
sumY = bPoly[i] * points[i].y;
}
int x, y;
x = (int) Math.round(sumX);
y = (int) Math.round(sumY);
g.drawLine(x offsetX, y offsetY, x offsetX, y offsetY);
}
这是添加点的方法(pointCount最初为0):points[pointCount] = new Point();
points[pointCount].x = evt.getX() - this.offsetX;
points[pointCount].y = evt.getY() - this.offsetY;
pointCount ;
this.drawScene();
解决方法:
问题出在这里for(int i = 0; i < pointCount; i ){
bPoly[i] = bernstein(t, pointCount, i 1);
}
bernstein方法中的第二个参数是不正确的.基本上如果我有3分,那应该是2而不是3分;bPoly[i] = bernstein(t, pointCount-1, i 1);来源:https://www.icode9.com/content-1-304651.html