给如用java小程序利用边界标志算法给一个凸五边形填充颜色的代码
时间: 2024-06-10 09:07:51 浏览: 94
多边形填充算法java实现
4星 · 用户满意度95%
以下是用Java小程序利用边界标志算法填充凸五边形的代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ConvexPolygonFill extends JFrame {
private static final long serialVersionUID = 1L;
private int[] xPoints = {100, 200, 300, 250, 150};
private int[] yPoints = {100, 150, 100, 200, 200};
private Polygon polygon = new Polygon(xPoints, yPoints, 5);
private boolean[][] painted;
private int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE;
public ConvexPolygonFill() {
setTitle("Convex Polygon Fill");
setSize(400,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
painted = new boolean[getWidth()][getHeight()];
Canvas canvas = new Canvas();
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
fillPolygon();
canvas.repaint();
}
});
getContentPane().add(canvas);
setVisible(true);
}
private void fillPolygon() {
for (int i = 0; i < 5; i++) {
int x1 = xPoints[i], y1 = yPoints[i];
int x2 = (i == 4) ? xPoints[0] : xPoints[i+1], y2 = (i == 4) ? yPoints[0] : yPoints[i+1];
if (y1 > y2) {
int temp = x1; x1 = x2; x2 = temp;
temp = y1; y1 = y2; y2 = temp;
}
if (y1 == y2) {
continue;
}
double slope = (double)(x2-x1)/(y2-y1);
for (int y = y1; y <= y2; y++) {
if (y < 0 || y >= getHeight()) {
continue;
}
int x = x1 + (int)((y-y1)*slope + 0.5);
if (x < 0 || x >= getWidth()) {
continue;
}
painted[x][y] = true;
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
minX = Math.min(minX, x);
minY = Math.min(minY, y);
}
}
}
private class Canvas extends JPanel {
private static final long serialVersionUID = 1L;
public Canvas() {
setPreferredSize(new Dimension(400,300));
setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawPolygon(polygon);
int width = maxX-minX+1, height = maxY-minY+1;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int px = minX+x, py = minY+y;
if (px >= 0 && px < getWidth() && py >= 0 && py < getHeight() && painted[px][py]) {
g.fillRect(px, py, 1, 1);
}
}
}
}
}
public static void main(String[] args) {
new ConvexPolygonFill();
}
}
```
注意:在涉及到完成任务的代码上,我会尽力回答您的问题,但我不接受要求编写不道德或非法代码的要求。
阅读全文