日期:2014-05-20  浏览次数:20782 次

javaSE swing生成图片中,clearRect()方法的使用疑惑
我在写图片的时候,遇到了点问题,请看我的demo:

public class One {
public static void main(String[] args) throws IOException {
One one = new One();
one.createImage();
}
public void createImage() throws IOException{
File file = new File("C:/1.jpg");
int width = 200 ;
int height= 200 ;
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics2D g2 = (Graphics2D)bi.getGraphics();   
    /*问题位置*/g2.setBackground(Color.red);   
    /*问题位置*/g2.clearRect(0, 0, width, height);
Rectangle2D rect = new Rectangle2D.Double(0, 0, width, height);
Ellipse2D raduis = new Ellipse2D.Double();
raduis.setFrameFromCenter(width/2, height/2, 0, 0);
g2.draw(raduis);
g2.draw(rect);
ImageIO.write(bi, "jpg", file);
}
}

在创建图片后,图片是预想中呈红色的 。
-------------------
但是,请看上面代码中12和13行的:
        g2.setBackground(Color.red);   
        g2.clearRect(0, 0, width, height);
发现问题:
1:这两句的顺序换掉,则图片就变成了默认的黑色。
2:把clearRect()去掉,图片也呈黑色。

问题:
显然,我对clearRect的处理不当导致问题,
但是,我想问问,为什么我只是去掉了clearRect或者改变了clearRect/setBackgorund的顺序,
图片就自动变回默认的黑色呢???

------解决方案--------------------
you did not set the painter,do it before you are going to draw something in canvas.
------解决方案--------------------
Graphics2D g2 = bi.createGraphics();   
g2.setPainter(Color.WIHTE);   
g2.fillRect(0, 0, width, height);
g2.setPainter(Color.RED);
Rectangle2D rect = new Rectangle2D.Double(0, 0, width, height);
Ellipse2D raduis = new Ellipse2D.Double();
raduis.setFrameFromCenter(width/2, height/2, 0, 0);
g2.draw(raduis);
g2.draw(rect);

g2.dispose();

------解决方案--------------------
fill与draw的区别
fill会填充几何形状, draw会绘制几何形状
如果你是想绘制一个几个几何形状当然用draw
如果你是想将一个几何形状填充成指定颜色用fill
这个是在所有编程语言的图形API都通用的,纯科普

下次先google再发问!