提起用编程语言绘制图像,大多数人想到的估计都是Python,比较Python真的简单易用,但是Java作为一门极受欢迎的语言,当然也有它的图像处理API,比如绘制这个太极图用的就是Java2D,而且Java运行速度要比Python更快
先看效果
代码
import javax.swing.*; import java.awt.*; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; public class GraphicsDemo extends JFrame{ public static void main(String[] args) { GraphicsDemo demo = new GraphicsDemo(); demo.setVisible(true);//设置可见 } public GraphicsDemo(){ this.setSize(300,200); this.setTitle("Java绘制太极"); JPanel panel = new JPanel(){ @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);//打开抗锯齿 Shape leftCircle = new Ellipse2D.Double(10,10,300,300); Shape rightCircle = new Ellipse2D.Double(10,10,300,300); Shape innerCircle1 = new Ellipse2D.Double(85,10,150,150); Shape innerCircle2 = new Ellipse2D.Double(85,160,150,150); Shape rectAngel1 = new Rectangle2D.Double(160,10,150,300); Shape rectAngel2 = new Rectangle2D.Double(10,10,150,300); Area left = new Area(leftCircle); Area right = new Area(rightCircle); Area area1 = new Area(rectAngel1); Area area2 = new Area(rectAngel2); left.subtract(area1); right.subtract(area2); Area inner1 = new Area(innerCircle1); Area inner2 = new Area(innerCircle2); left.add(inner1); right.add(inner2); right.subtract(inner1); Shape minorWhiteCircle = new Ellipse2D.Double(150,70,20,20); Shape minorBlackCircle = new Ellipse2D.Double(150,230,20,20); g2.setPaint(Color.WHITE); g2.fill(left); g2.setPaint(Color.BLACK); g2.fill(right); g2.fill(minorWhiteCircle); g2.setPaint(Color.WHITE); g2.fill(minorBlackCircle); g2.dispose(); } }; this.add(panel);//添加到当前 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗口关闭程序关闭,相当于System.exit } }
代码解析
JavaArea对图形的布尔操作如下
Uion(+):保留两个图形的重叠部分
Subtraction(-):从第一个图形中减去第二个部分的重叠部分
Innersection(&):只保留两个图形的重叠部分
Exclusion-or(^):保留两个图形的不重叠部分
代码中区域的划分参考
建议看着代码自己理解比较好,或者直接拿去用