使用Graphics2D画表格

2023-11-10 23:50
文章标签 使用 graphics2d 画表格

本文主要是介绍使用Graphics2D画表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在机器人需要发表格图片需求,我搜索了一些第三方包,最终使用了java内置的Graphics2D来画表格生成jpg图片,再通过cq语句发送。

表格图片,需要有标题,表格头,表格内容,将表格头和表格前三名设置背景色。

使用Graphics2D画图,需要画横线,竖线,还有字体,其中选择位置进行渲染比较繁琐。所以我将画表格分为几部分来画

1、先定图片大小

图片的高度,等于标题加表格头加表格内容所有高度再加上余留边角部分大概20个像素

图片的宽度,等于表格头的项数加上余留边角部分大概20个像素

 int rows = 0;int maxfont = 0;if (allValue != null && allValue.size() > 0) {rows += (2+allValue.size());}for (List<String> strings : allValue) {maxfont = strings.get(0).length()>maxfont?strings.get(0).length():maxfont;}// 实际数据行数+标题+备注//初始化宽度int numwidth = 50;//序号宽度int totalrow = 1+rows;//总行数int namewidth = maxfont * 22;//名字列宽度int otherwidth = 80;//其他列宽度int imageWidth = numwidth + namewidth  + otherwidth*(headers.length-2) + 20;//图片总宽度//初始化高度int imageHeight = totalrow * 30 + 20;//图片总高度int rowheight = 30;//行高//图片边框留白int startHeight = 10;//余留上方10像素int startWidth = 10;//余留左方10像素//创建Graphics2D对象,用图片缓存流BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics = image.createGraphics();

2、画背景

通过刚刚计算的图片的高度和宽度,画一张白色的画补作为图片总背景

graphics.setColor(Color.WHITE);graphics.fillRect(0, 0, imageWidth, imageHeight);

再将表格头和前三名的背景画上,通过计算再使用fillRect画上

    //画表头背景graphics.setColor(new Color(150,0,0));if (allValue != null && allValue.size() > 0) {graphics.fillRect(startWidth + 1, startHeight +  rowheight + 1, imageWidth - startWidth - 6, rowheight - 1);}//画前三名背景int redstartH = 2;graphics.setColor(new Color(190,25,0));for (int temp = 0; temp < allValue.size(); temp++) {List strings = allValue.get(temp);if (strings != null) {graphics.fillRect(startWidth + 1,startHeight + redstartH*rowheight +1 , imageWidth - startWidth - 6,rowheight - 1);}redstartH++;if(temp==2)break;}

3、画表格体

画表格体,先画横线再画竖线,通过上方留白高度+行高*n来画横线,通过左方留白宽度+各列宽度来画竖线。

// 画横线for (int j = 0; j < totalrow - 1; j++) {graphics.setColor(Color.gray);graphics.drawLine(startWidth, startHeight + (j + 1) * rowheight, imageWidth - 5,startHeight + (j + 1) * rowheight);}int rightLine;// 画竖线graphics.setColor(Color.gray);if (allValue != null && allValue.size() > 0) {for (int k = 0; k < headers.length+1; k++) {rightLine = getRightMargin(k,startWidth, namewidth,otherwidth,imageWidth);graphics.drawLine(rightLine, startHeight + rowheight, rightLine,startHeight + (allValue.size()+2)*rowheight);}}

4、写标题,表头

已计算出每行的高度,把标题写在第一行,表头写在第二行。通过累加行高得出些的位置。

因为标题从第一行开始,表格头从第二行开始,内容从第三行开始,所以设置了startH来控制画图位置

// 设置字体,准备写入文字Font font = new Font("宋体", Font.BOLD, 20);graphics.setFont(font);graphics.setColor(Color.black);// 写标题if (allValue != null && allValue.size() > 0) {graphics.drawString(titles, imageWidth / 3 + startWidth+30, startHeight + rowheight - 10);}// 写入表头int startH = 2;graphics.setColor(Color.WHITE);font = new Font("宋体", Font.BOLD, 20);graphics.setFont(font);if (allValue != null && allValue.size() > 0) {for (int m = 0; m < headers.length; m++) {int strWidth = graphics.getFontMetrics().stringWidth(headers[m]);rightLine = getRightMargin(m,startWidth, namewidth,otherwidth,imageWidth);if(m==0)rightLine = rightLine + (numwidth-strWidth)/2;else if(m==1)rightLine = rightLine + (namewidth-strWidth)/2;elserightLine = rightLine + (otherwidth-strWidth)/2;graphics.drawString(headers[m], rightLine,startHeight + startH*rowheight  - 10);}}// 写入内容startH = 3;graphics.setColor(Color.white);graphics.setFont(new Font("宋体", Font.BOLD, 20));if (allValue != null && allValue.size() > 0) {for (int n = 0; n < allValue.size(); n++) {if (n == 3) {graphics.setColor(Color.black);graphics.setFont(new Font("宋体", Font.PLAIN, 20));}List<String> arr = allValue.get(n);for (int l = 0; l < arr.size() + 1; l++) {rightLine = getRightMargin(l, startWidth, namewidth, otherwidth, imageWidth) + 5;if (l == 0) {int strWidth = graphics.getFontMetrics().stringWidth(String.valueOf(n + 1));graphics.drawString(String.valueOf(n + 1), rightLine + (numwidth - strWidth) / 2 - 5,startHeight + rowheight * (n + startH) - 10);} else {int strWidth = graphics.getFontMetrics().stringWidth(arr.get(l - 1));if (l == 1)graphics.drawString(arr.get(l - 1), rightLine,startHeight + rowheight * (n + startH) - 10);elsegraphics.drawString(arr.get(l - 1), rightLine + (otherwidth - strWidth) / 2 - 5,startHeight + rowheight * (n + startH) - 10);}}}}

5、消除锯齿

因为2D画图画字体会有锯齿,而graphics2D类有抗锯齿和画笔柔顺的开关,设置如下

   graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);Stroke s = new BasicStroke(imageWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);graphics.setStroke(s);

6、生成图片

然后创建一个1.jpg将图片的缓存来写出到图片文件中,在项目的相对路径中就有一张图片1.jpg

graphics.drawImage(image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH), 0, 0, null);String path = "1.jpg";ImageIO.write(image, "jpg", new File(path));

测试画图效果

List<List<List<String>>> allValue = new ArrayList<>();List<List<String>> contentArray1 = new ArrayList<>();for(int i = 0;i<10;i++){contentArray1.add(Arrays.asList(
new String[]{"谭宇","300","5.00","1.00","1234","1234","1234","100"}));}String[] headTitles = 
new String[]{"序号","名字","成绩","击键","码长","退格","回改","选重","错字"};String titles = "跟打成绩";try {graphicsGeneration(contentArray1,titles,headTitles);} catch (Exception e) {e.printStackTrace();}
14899865-56be6c0dad522194.png
image.png

例子源码

package ImgTest;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class imatest {public static String graphicsGeneration(List<List<String>> allValue, String titles, String[] headers ) throws Exception {int rows = 0;int maxfont = 0;if (allValue != null && allValue.size() > 0) {rows += (2+allValue.size());}for (List<String> strings : allValue) {maxfont = strings.get(0).length()>maxfont?strings.get(0).length():maxfont;}// 实际数据行数+标题+备注int numwidth = 50;int totalrow = 1+rows;int namewidth = maxfont * 22;int otherwidth = 80;int imageWidth = numwidth + namewidth  + otherwidth*(headers.length-2) + 20;int imageHeight = totalrow * 30 + 20;int rowheight = 30;int startHeight = 10;int startWidth = 10;BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics = image.createGraphics();graphics.setColor(Color.WHITE);graphics.fillRect(0, 0, imageWidth, imageHeight);//画表头背景graphics.setColor(new Color(150,0,0));if (allValue != null && allValue.size() > 0) {graphics.fillRect(startWidth + 1, startHeight +  rowheight + 1, imageWidth - startWidth - 6, rowheight - 1);}//画前三名背景int redstartH = 2;graphics.setColor(new Color(190,25,0));for (int temp = 0; temp < allValue.size(); temp++) {List strings = allValue.get(temp);if (strings != null) {graphics.fillRect(startWidth + 1,startHeight + redstartH*rowheight +1 , imageWidth - startWidth - 6,rowheight - 1);}redstartH++;if(temp==2)break;}// 画横线for (int j = 0; j < totalrow - 1; j++) {graphics.setColor(Color.gray);graphics.drawLine(startWidth, startHeight + (j + 1) * rowheight, imageWidth - 5,startHeight + (j + 1) * rowheight);}int rightLine;// 画竖线graphics.setColor(Color.gray);if (allValue != null && allValue.size() > 0) {for (int k = 0; k < headers.length+1; k++) {rightLine = getRightMargin(k,startWidth, namewidth,otherwidth,imageWidth);graphics.drawLine(rightLine, startHeight + rowheight, rightLine,startHeight + (allValue.size()+2)*rowheight);}}// 设置字体,准备写入文字Font font = new Font("宋体", Font.BOLD, 20);graphics.setFont(font);graphics.setColor(Color.black);// 写标题if (allValue != null && allValue.size() > 0) {graphics.drawString(titles, imageWidth / 3 + startWidth+30, startHeight + rowheight - 10);}// 写入表头int startH = 2;graphics.setColor(Color.WHITE);font = new Font("宋体", Font.BOLD, 20);graphics.setFont(font);if (allValue != null && allValue.size() > 0) {for (int m = 0; m < headers.length; m++) {int strWidth = graphics.getFontMetrics().stringWidth(headers[m]);rightLine = getRightMargin(m,startWidth, namewidth,otherwidth,imageWidth);if(m==0)rightLine = rightLine + (numwidth-strWidth)/2;else if(m==1)rightLine = rightLine + (namewidth-strWidth)/2;elserightLine = rightLine + (otherwidth-strWidth)/2;graphics.drawString(headers[m], rightLine,startHeight + startH*rowheight  - 10);}}// 写入内容startH = 3;graphics.setColor(Color.white);graphics.setFont(new Font("宋体", Font.BOLD, 20));if (allValue != null && allValue.size() > 0) {for (int n = 0; n < allValue.size(); n++) {if (n == 3) {graphics.setColor(Color.black);graphics.setFont(new Font("宋体", Font.PLAIN, 20));}List<String> arr = allValue.get(n);for (int l = 0; l < arr.size() + 1; l++) {rightLine = getRightMargin(l, startWidth, namewidth, otherwidth, imageWidth) + 5;if (l == 0) {int strWidth = graphics.getFontMetrics().stringWidth(String.valueOf(n + 1));graphics.drawString(String.valueOf(n + 1), rightLine + (numwidth - strWidth) / 2 - 5,startHeight + rowheight * (n + startH) - 10);} else {int strWidth = graphics.getFontMetrics().stringWidth(arr.get(l - 1));if (l == 1)graphics.drawString(arr.get(l - 1), rightLine,startHeight + rowheight * (n + startH) - 10);elsegraphics.drawString(arr.get(l - 1), rightLine + (otherwidth - strWidth) / 2 - 5,startHeight + rowheight * (n + startH) - 10);}}}}graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);Stroke s = new BasicStroke(imageWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);graphics.setStroke(s);graphics.drawImage(image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH), 0, 0, null);String path = "1.jpg";ImageIO.write(image, "jpg", new File(path));return path;}/*** 获取竖线和文字的水平位置* @param k* @param startWidth* @param namewidth* @param otherwidth* @param imageWidth* @return*/private static int getRightMargin(int k, int startWidth, int namewidth,int otherwidth, int imageWidth) {int rightLine = 0;if (k == 0) {rightLine = startWidth;} else if (k == 1) {rightLine = startWidth + 50;} else if (k == 2) {rightLine = startWidth + 50 + namewidth;} else if (k >= 3 &&k<9) {rightLine = startWidth + +50 + namewidth + (k - 2) * otherwidth;} else if (k == 9)rightLine = imageWidth - 5;return rightLine;}public static void initChartData(){List<List<String>> contentArray1 = new ArrayList<>();for(int i = 0;i<10;i++){contentArray1.add(Arrays.asList(new String[]{"谭宇","300","5.00","1.00","1234","1234","1234","100"}));}String[] headTitles = new String[]{"序号","名字","成绩","击键","码长","退格","回改","选重","错字"};String titles = "跟打成绩";try {graphicsGeneration(contentArray1,titles,headTitles);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {initChartData();}
}

这篇关于使用Graphics2D画表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/386114

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他