java 多边形填充颜色,java swing:多边形填充颜色问题

本文探讨了Java图形编程中遇到的一个问题,即自相交多边形填充。作者指出,当尝试使用`fillPolygon`方法填充一个自相交的多边形时,由于填充规则导致内部区域无法正确识别。解决方案是将多边形拆分为互不相交的部分。文章通过代码示例展示了问题所在,并提出了可能的解决策略。
摘要由CSDN通过智能技术生成

Could any body diagnose the problem I am facing?

As you run the demo you can see the middle part left blank, I need to fill the entire area..

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Polygon;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class FillDemo

{

public static void main(String aths[])

{

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pnl = new PolygonDemo();

pnl.setSize(100, 200);

f.getContentPane().add(pnl);

f.setSize(400,280);

f.setLocation(200,200);

f.setVisible(true);

}

}

class PolygonDemo extends JPanel

{

public PolygonDemo()

{

setBackground(Color.white);

}

protected void paintComponent(Graphics g)

{

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

Polygon p=new Polygon();

p.addPoint(100,0);

p.addPoint(100,100);

p.addPoint(0,100);

p.addPoint(0,0);

p.addPoint(80,0);

p.addPoint(80,20);

p.addPoint(40,20);

p.addPoint(40,40);

p.addPoint(80,40);

p.addPoint(80,100);

p.addPoint(20,100);

p.addPoint(20,80);

p.addPoint(60,80);

p.addPoint(60,60);

p.addPoint(20,60);

p.addPoint(20,0);

p.addPoint(0,0);

g2.setColor(Color.BLACK);

g2.draw(p);

g2.setColor(new Color(120,250,100));

g2.fillPolygon(p);

//g2.fillPolygon(p.xpoints,p.ypoints,p.npoints);

}

}

Many thanks in advance

解决方案

Your polygon intersects with itself. The fillPolygon method can not clearly decide which point is in and which is out. From the fillPolygon javadoc:

The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.

Perhaps you can split your polygon into three single ones.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值