用java实现三角形三个顶点的颜色分别为红绿蓝,使用有效边表算法填充三角形
时间: 2023-06-18 12:03:10 浏览: 134
计算机图形学使用有效边表法完成多边形的扫描转换并填充颜色
以下是使用Java实现三角形填充的有效边表算法代码示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TriangleFill extends JPanel {
private static final long serialVersionUID = 1L;
private List<Edge> edges;
private List<Integer> activeList;
public TriangleFill() {
edges = new ArrayList<Edge>();
activeList = new ArrayList<Integer>();
edges.add(new Edge(new Point(100, 100), new Point(200, 200), Color.RED));
edges.add(new Edge(new Point(200, 200), new Point(300, 100), Color.GREEN));
edges.add(new Edge(new Point(300, 100), new Point(100, 100), Color.BLUE));
Collections.sort(edges);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Edge edge : edges) {
g.setColor(edge.color);
g.drawLine(edge.start.x, edge.start.y, edge.end.x, edge.end.y);
}
fill(g);
}
private void fill(Graphics g) {
int yMin = edges.get(0).start.y;
int yMax = edges.get(edges.size() - 1).end.y;
for (int y = yMin; y <= yMax; y++) {
updateActiveList(y);
Collections.sort(activeList);
for (int i = 0; i < activeList.size(); i += 2) {
int xMin = activeList.get(i);
int xMax = activeList.get(i + 1);
g.drawLine(xMin, y, xMax, y);
}
}
}
private void updateActiveList(int y) {
for (Edge edge : edges) {
if (edge.start.y <= y && edge.end.y > y) {
double x = (y - edge.start.y) * (edge.end.x - edge.start.x)
/ (double) (edge.end.y - edge.start.y) + edge.start.x;
if (!activeList.contains((int) x)) {
activeList.add((int) x);
}
} else if (edge.end.y == y) {
activeList.remove((Integer) edge.end.x);
}
}
}
private class Edge implements Comparable<Edge> {
Point start;
Point end;
Color color;
public Edge(Point start, Point end, Color color) {
if (start.y < end.y) {
this.start = start;
this.end = end;
} else {
this.start = end;
this.end = start;
}
this.color = color;
}
public int compareTo(Edge edge) {
return start.y - edge.start.y;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.add(new TriangleFill());
frame.setVisible(true);
}
}
```
代码中,我们先定义了三个点的颜色为红、绿、蓝,然后将它们连成三角形,并按照起始点的y坐标排序。接着,在`paintComponent()`方法中,我们绘制出这个三角形,然后调用`fill()`方法填充其内部。`fill()`方法遍历三角形内部的每一行,每次更新活动边表,并按照x坐标排序,然后绘制出每一行的所有线段。`updateActiveList()`方法用于更新活动边表,它首先判断当前边是否与当前行有交点,如果有,则计算该点的x坐标,并将其加入活动边表中;否则,如果当前边的结束点恰好是当前行,则将该结束点从活动边表中移除。最后,定义一个边类`Edge`用于存储边的起始点、结束点和颜色,实现`Comparable`接口用于排序,然后在`main()`方法中创建一个JFrame并将三角形填充面板添加到其中,运行程序即可看到填充后的三角形。
阅读全文