墨水屏显示原理
电子墨水是一种具有反射性质的物质,它由微小的颗粒组成,这些颗粒可以根据电场的变化在屏幕上显示出不同的图像或文字。墨水屏的显示原理是利用电场的作用使得电子墨水中的颗粒在屏幕上移动。当电场施加在电子墨水上时,颗粒会根据电场的方向移动,其中一些颗粒会被吸附到屏幕的表面上,形成可见的图像或文字。
需求说明
一般在墨水屏上想要显示文字可通过PCtoLCD软件对文件进行取模后再将16进制数据烧写进墨水屏驱动中。但是目前有个需求就是想要在Web端对墨水屏中的数据内容进行更新并通过Tcp将数据发送到墨水屏中实现自动更新。由于Web端使用Java语言搭建,需要使用Java编写对文字进行取模的算法,看了网上没有什么教程于是自己进行了简单实现,最后将结果在墨水屏中测试得到验证。
工具类代码
初始化该类对象需要传入单个文字的宽和高,字体文件路径,需要转换的字符串,带处理字符串个数,处理结果存储在byte[] result结果中,可以直接将结果传输到墨水屏中。还提供了字符串位图以及十六进制结果打印函数。
package Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FontConversionUtil {
//字宽
private int width;
//字高
private int height;
//字数量
private int count;
//字体路径
private String fontPath;
//待取模字符串
private String target;
//结果
private byte[] result;
/**
* 构造方法
* @return
*/
public FontConversionUtil(int width, int height, String fontPath, String target,int count) {
this.width = width;
this.height = height;
this.fontPath = fontPath;
this.target = target;
this.count = count;
}
/**
* 转换
* @return
*/
public byte[] Conversion(){
BufferedImage image = new BufferedImage(width*count, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
try {
// 加载字体文件
File fontFile = new File(fontPath);
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
// 设置字体样式和大小
font = font.deriveFont(Font.PLAIN, width);
g2d.setFont(font);
g2d.setColor(Color.BLACK);
// 第三个参数调整字体上下偏移
g2d.drawString(target, 0, width*6/7);
g2d.dispose();
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
byte c = 0x00;
result = new byte[height*width*count/8];
//位运算
for (int y = 0; y < height; y++) {
for (int x = 0; x < width*count/8; x++) {
c = 0x00;
for (int i = 0; i < 8; i++) {
c = (byte) (c<<1);
if(image.getRGB(x*8+i, y) != Color.BLACK.getRGB()){
c = (byte) (c | 0x01);
}
}
result[x+y*width*count/8]=c;
}
}
return result;
}
/**
* 打印16进制
* @return
*/
public void print16(){
StringBuilder stringBuilder = new StringBuilder();
int j = 0;
for (byte b : result) {
stringBuilder.append(String.format("0x%02X", b)).append(",");
j++;
if (j == width*count/8) {
stringBuilder.append("\n");
j = 0;
}
}
System.out.println(stringBuilder);
}
/**
* 打印位图
* @return
*/
public void printBitMap(){
int j = 0;
for (byte b:result){
for (int i = 7; i >= 0; i--) {
int bit = (b >> i) & 1; // 右移并且按位与操作
System.out.print(bit);
}
j++;
if(j==width*count/8){
System.out.println();
j=0;
}
}
}
}
使用案例
package Font;
public class Test {
public static void main(String[] args) {
FontConversionUtil fontConversionUtil = new FontConversionUtil(32, 32, "src/main/java/Font/SIMHEI.TTF", "我爱你",3);
byte[] arr = fontConversionUtil.Conversion();
fontConversionUtil.printBitMap();
fontConversionUtil.print16();
}
}
打印结果