我有一个 JPanel 200x200。
我尝试创建一个函数,该函数将在 JPanel 的边界内生成随机抛物线,并限制高度不能低于 100(屏幕中间),我基本上想围绕这些抛物线移动形状
这是我用来开始使用的一些代码:
Random random = new Random(); int y; int x;
int size = random.nextInt(10);
int translation = random.nextInt(50);
int height = random.nextInt(100) - 200; //between 100 and 200
//抛物线函数:y = ((x/7 - 30))^2
//x 和 y 是绘制形状的坐标
while(y != 200){
y = (float)Math.pow((float)xloc / size - translation ,2) + height;
x++;
}
我一直在研究 FlatteningPathIterator 但不太确定如何使用它们。我的功能
y = (float)Math.pow((float)xloc / size - translation ,2) + height;`
有时打印抛物线在边界之外,我如何编辑它以在边界内打印抛物线?
最佳答案
有一个名为 Quad2dCurve 的 Java Swing 形状生成器。 getPathIterator
调用为您提供曲线上点的枚举器。
这里是一些示例代码:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;
final class TestCanvas extends JComponent {
int size = 200;
int n = 10;
float[] ph = new float[n];
float[] pw = new float[n];
float[] px = new float[n];
Random gen = new Random();
TestCanvas() {
makeRandomParabolas();
setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
makeRandomParabolas();
repaint();
float [] coords = new float [6];
for (int i = 0; i < n; i++) {
PathIterator pi = getQuadCurve(i).getPathIterator(null, 0.1);
System.out.print(i + ":");
while (!pi.isDone()) {
switch (pi.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
System.out.print(" move to");
break;
case PathIterator.SEG_LINETO:
System.out.print(" line to");
break;
default:
System.out.print(" unexpected");
break;
}
System.out.println(" (" + coords[0] + "," + coords[1]+")");
pi.next();
}
System.out.println();
}
}
});
}
QuadCurve2D.Float getQuadCurve(int i) {
return new QuadCurve2D.Float(px[i] - pw[i], size,
px[i], size - (2 * ph[i]),
px[i] + pw[i], size);
}
void makeRandomParabolas() {
for (int i = 0; i < n; i++) {
float x = 0.2f + 0.6f * gen.nextFloat();
px[i] = size * x;
pw[i] = size * (Math.min(x, 1 - x) * gen.nextFloat());
ph[i] = size * (0.5f + 0.5f * gen.nextFloat());
}
}
@Override
protected void paintComponent(Graphics g0) {
Graphics2D g = (Graphics2D) g0;
for (int i = 0; i < n; i++) {
g.draw(getQuadCurve(i));
}
}
}
public class Main extends JFrame {
public Main() {
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new TestCanvas());
getContentPane().setPreferredSize(new Dimension(200, 200));
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main().setVisible(true);
}
});
}
}
关于java - 边界内的抛物线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240129/