signed

QiShunwang

“诚信为本、客户至上”

java 2d画图示例分享(用java画图)

2021/6/9 5:06:18   来源:

Java 2D API通过扩展抽象窗口工具箱(AWT),为Java程序提供了二维图像,文本和图形的功能。这个复杂的渲染包支持线形图像,文本和图形,为富用户界面,复杂绘图程序和图像处理器开发者提供灵活的,功能强大的框架。Java 2D对象出现在一个平面中,称为用户坐标系空间,和设备坐标系空间。当对象在屏幕或打印机中渲染时,用户空间坐标系被转换成设备空间坐标系。

复制代码 代码如下:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;

import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

public class test {
    public static void main(String[] args) throws IOException {
        int width = 800;
        int height = 800;

        BufferedImage image = new BufferedImage(
                width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, width, height);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        Random random = new Random();
        int wo = 0;
        int ho = 0;
        for (int i = 0; i < 10; i++) {
         int x = random.nextInt(width);
         int y = random.nextInt(height);
            g2d.setColor(new Color(random.nextInt(256),
                    random.nextInt(256), random.nextInt(256)));
            g2d.setStroke(new BasicStroke(1));

            g2d.drawString("node"+i, x, y);
            g2d.drawArc(x, y, 20, 20, 0, 360);
            if(i!=0){
             g2d.drawLine(wo, ho, x, y);
            }
            wo = x;
            ho = y;
        }
        g2d.dispose();
       

        ImageWriter writer = null;
        ImageTypeSpecifier type =
            ImageTypeSpecifier.createFromRenderedImage(image);
        Iterator iter = ImageIO.getImageWriters(type, "jpg");
        if (iter.hasNext()) {
            writer = (ImageWriter)iter.next();
        }
        if (writer == null) {
            return;
        }
        IIOImage iioImage = new IIOImage(image, null, null);
        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality((float) ((10) / 10.0));
        ImageOutputStream outputStream =
          ImageIO.createImageOutputStream(new File("C:/test.jpg"));
        writer.setOutput(outputStream);
        writer.write(null, iioImage, param);
    }
}

您可能感兴趣的文章:
  • java分形绘制科赫雪花曲线(科赫曲线)代码分享
  • Java Swing中的文本框(JTextField)与文本区(JTextArea)使用实例
  • Java Swing中的下拉式菜单(menu)、弹出式菜单(JPopupMenu)、选项卡窗体(JTabbedPane)组件使用案例
  • Java Swing中的表格(JTable)和树(JTree)组件使用实例
  • java swing中实现拖拽功能示例
  • 使用java swing实现qq登录界面示例分享
  • java swing标准对话框具体实现
  • java基于swing实现的连连看代码
  • java基于swing实现的五子棋游戏代码
  • Java图形用户界面设计(Swing)的介绍
  • Java实现的简单画图板示例