如何填充形状外的颜色(椭圆形)

问题描述 投票:4回答:3

我希望能够使用Graphics2D实例绘制BufferedImage,并在Shape外部填充Color。如果这是一个像Rectangle这样的形状,那将很容易,但我需要使用的Shape是一个Circle。

使用Color填充圆圈很容易,只需写下:

Graphics2D g2d = <my_image>.createGraphics();
...
g2d.fillOval(x, y, width, height);

但是,我想要的是与此相反。我没有用数字(x,y,宽度,高度)填充椭圆形内部,而是想填充它外面的所有东西。

我在这方面收效甚微。我想到的唯一一件事就是在我希望圆圈占据的空间周围画出巨大的拱门,因为我很难搞清楚数学计算。

编辑:为什么我不能只填充整个图像然后画圆圈,是因为圆圈中的东西不是单一的颜色,而是我想要拍摄一张图像(任何图像,如我自己的照片)并且能够在该图像中间的圆周周围添加单一颜色。因此,在绘制它之前,圆圈中间的任何东西都已存在,并且它不是首先由代码绘制的东西。

java graphics2d shapes fill
3个回答
1
投票

以下是基于Java anti fillRect (fill everything outside of said rectangle)答案的示例。

它使用substractjava.awt.geom.Area方法。

        Area outter = new Area(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
        int x = (img.getWidth() / 4) ;
        int y = (img.getHeight() / 4);
        Ellipse2D.Double inner = new Ellipse2D.Double(x,y, img.getWidth()/2, img.getHeight()/2);
        outter.subtract(new Area(inner));// remove the ellipse from the original area

        g2d.setColor(Color.BLACK);
        g2d.fill(outter);

没有作物(即没有g2d.fill(outter)部分):

enter image description here

作物(外部填充黑色):

enter image description here


0
投票

如果你要让背景变成纯色并且你留下椭圆形白色的内部怎么办?

 JPanel.setBackgroundColor(Color.black);

然后绘制并填充你的椭圆形

g2d.setColor(Color.white);
g2d.drawOval(x, y, width, height);
g2d.fillOval(x, y, width, height);

这应该是一个例子来对比他们


0
投票

数学是这样的:

如果你知道圆是(x,y)并且半径为r

for(i=0; i<width; i++)
for(j=0; j<height; j++)
  if((i-x)*(i-x)+(j-y)*(j-y))>r*r)
    b.setRGB(i, j, 0xff0000);

这将在圆圈外面绘制BufferedImage b红色。

© www.soinside.com 2019 - 2024. All rights reserved.