JavaSwing图形界面编程之BufferedImage(一)

时间:2021-08-19 11:42:29
package three.day.frame;


import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;


import javax.swing.JFrame;
import javax.swing.JPanel;


public class BufferedImage01
{
public BufferedImage01()
{
JFrame f = new JFrame("draw geom");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(350, 50);
drawPanel dp = new drawPanel();
dp.setPreferredSize(new Dimension(600,600));
Container ct = f.getContentPane();
dp.setBackground(Color.WHITE);
ct.add(dp,BorderLayout.CENTER);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args)
{
new BufferedImage01();
}
}
class drawPanel extends JPanel
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Line2D.Double ln1 = new Line2D.Double(20.0,20.0,80.0,40.0);
QuadCurve2D.Double qc = new QuadCurve2D.Double(130.0,30.0,150.0,50.0,170.0,20.0);
CubicCurve2D.Double cc = new CubicCurve2D.Double(220.0,40.0,240.0,60.0,260.0,20.0,300.0,35.0);
Rectangle2D.Double rect = new Rectangle2D.Double(10,10,100,100);
RoundRectangle2D.Double rRect = new RoundRectangle2D.Double(10,80, 200, 100, 20, 20);
Ellipse2D.Double ellipse = new Ellipse2D.Double(0,300, 100, 100);
Arc2D.Double arc = new Arc2D.Double(200,200, 200, 200, 0, 90,/*Arc2D.OPEN Arc2D.CHORD*/Arc2D.PIE );
GeneralPath polygon =new GeneralPath();
polygon.moveTo(200, 200);
polygon.lineTo(400, 400);
polygon.lineTo(400, 200);
polygon.closePath();
BasicStroke bs = new BasicStroke(5);
g2.translate(300, 100);
g2.rotate(45*Math.PI/180);
g2.setStroke(bs);
g2.setPaint(Color.red);
g2.draw(ln1);
g2.draw(qc);
g2.draw(cc);
g2.draw(rect);
g2.draw(ellipse);
g2.draw(rRect);
g2.draw(arc);
g2.setTransform(new AffineTransform());
BufferedImage bi = new BufferedImage(400,400, BufferedImage.TYPE_INT_ARGB);
Graphics2D gdi =  (Graphics2D) bi.getGraphics();
gdi.setColor(Color.YELLOW);
   gdi.fill(rect);
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN,1.0f);
gdi.setComposite(ac);
gdi.setPaint(Color.green);

gdi.fill(ellipse);
gdi.fill(rRect);
gdi.fill(arc);
gdi.setPaint(Color.darkGray);
gdi.draw(polygon);
g2.drawImage(bi, null, 0, 0);
}
}