java字符串输出换行_java 打印例子(字符串换行问题)

本文详细介绍了如何在Java中进行字符串打印,并处理换行问题。通过`Graphics2D`对象设置字体、颜色及打印起点,展示了一个完整的打印图片和文字的例子。同时,文章提出了按像素判断换行的思路,以解决英文和汉字宽度不一致带来的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.打印例子

java打印中最关键的就是每一个绘图函数 g2.drawString(str, x, y ) 中的起点坐标(x,y)

import java.awt.BasicStroke;

import java.awt.Color;

import java.awt.Component;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.print.Book;

import java.awt.print.PageFormat;

import java.awt.print.Paper;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;

/**

* 打印图片和文字

*

* @author wfg

*

*/

public class PrintSalesSlip implements Printable {

/** */

/**

* @param Graphic指明打印的图形环境

* @param

* PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英才的1/72,1英寸为25.4毫米。A4纸大致为595×842点)

* @param pageIndex指明页号(80毫米:226.7点,58毫米:164.4)

*/

public int print(Graphics gra, PageFormat pf, int pageIndex)

throws PrinterException {

Component c = null;

// print string

// 转换成Graphics2D

Graphics2D g2 = (Graphics2D) gra;

// 设置打印颜色为黑色

g2.setColor(Color.black);

// 打印起点坐标

double x = pf.getImageableX();//返回与此 PageFormat 相关的 Paper 对象的可成像区域左上方点的 x 坐标。

double y = pf.getImageableY();

switch (pageIndex) {

case 0:

// 设置打印字体(字体名称、样式和点大小)(字体名称可以是物理或者逻辑名称)

// Java平台所定义的五种字体系列:Serif、SansSerif、Monospaced、Dialog 和 DialogInput

Font font = new Font("宋体", Font.PLAIN, 12);

g2.setFont(font);// 设置字体

// BasicStroke bs_3=new BasicStroke(0.5f);

float[] dash1 = { 2.0f };

// 设置打印线的属性。

// 1.线宽 2、3、不知道,4、空白的宽度,5、虚线的宽度,6、偏移量

g2.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_BUTT,

BasicStroke.JOIN_MITER, 2.0f, dash1, 0.0f));

// g2.setStroke(bs_3);//设置线宽

float fontHeigth1 = font.getSize2D();

// -1- 用Graphics2D直接输出

// 首字符的基线(右下部)位于用户空间中的 (x, y) 位置处

//g2.drawLine(10,10,200,300);

String str1 ="xxxxxxxxxxxxxxxxxx";

g2.drawString(str1, (int)x, (int)y + fontHeigth1);

String str2 = "139";

g2.drawString(str2, (int)x, (int)y + fontHeigth1*2+10);

Font font2 = new Font("宋体", Font.PLAIN, 9);

g2.setFont(font2);// 设置字体

g2.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_BUTT,

BasicStroke.JOIN_MITER, 2.0f, dash1, 0.0f));

float fontHeigth2 = (int)font.getSize2D();

int tempHeight = (int) (fontHeigth1*2+10);

String str3 ="行行行行行行惺惺惜惺惺";

g2.drawString(str3, (int)x, (int)y + fontHeigth2+10 +tempHeight);

String str4 ="xxxxxxxxxxxxxx嘻嘻嘻";

g2.drawString(str4, (int)x, (int)y + fontHeigth2*2+10 +tempHeight);

String str5 ="新行行行行行行行行行";

g2.drawString(str5, (int)x, (int)y + fontHeigth2*3+10 +tempHeight);

String str6 ="惺惺相惜休息休息想";

g2.drawString(str6, (int)x, (int)y + fontHeigth2*4+20 +tempHeight);

String str7 ="xxxxxxxx";

g2.drawString(str7, (int)x, (int)y + fontHeigth2*5+20 +tempHeight);

String str8 ="xxxxxxxxxxxxxxxxx";

g2.drawString(str8, (int)x, (int)y + fontHeigth2*6+20 +tempHeight);

Image src = Toolkit.getDefaultToolkit().getImage("f:/barcode2.jpg");

g2.drawImage(src, (int) x, (int)( y + fontHeigth2*6+50 +tempHeight+10),150,70, c);//打印条形码

int img_Height = src.getHeight(c);

int img_width = src.getWidth(c);

return PAGE_EXISTS;

default:

return NO_SUCH_PAGE;

}

}

public static void main(String[] args) {

// 通俗理解就是书、文档

Book book = new Book();

// 设置成竖打

PageFormat pf = new PageFormat();

pf.setOrientation(PageFormat.PORTRAIT);

/*static int LANDSCAPE

原点位于纸张的左下方,x 的方向从下到上,y 的方向从左到右。

static int PORTRAIT

原点在纸张的左上方,x 指向右方,y 指向下方。

static int REVERSE_LANDSCAPE

原点位于纸张的右上方,x 的方向从上到下,y 的方向从右到左。 */

//(页面大小以点为计量单位,1点为1英寸的1/72,1英寸为25.4毫米。A4纸大致为595×842点)

// 通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。

Paper p = new Paper();

///

System.out.println("1高:"+p.getHeight()+"-宽:"+p.getWidth());

p.setSize(227, 300);// 纸张大小 设置此 Paper 对象的宽和高,它表示要用来打印的页面的属性

p.setImageableArea(10, 10, 227, 300);//设置此 Paper 的可成像区域。

//A4(595 X 842)设置打印区域,其实0,0应该是72,72,因为A4纸的默认X,Y边距是72

System.out.println("2高:"+p.getHeight()+"-宽:"+p.getWidth());

pf.setPaper(p);

// 把 PageFormat 和 Printable 添加到书中,组成一个页面

book.append(new PrintSalesSlip(), pf);

// 获取打印服务对象

PrinterJob job = PrinterJob.getPrinterJob();

// 设置打印类

job.setPageable(book);

try {

// 可以用printDialog显示打印对话框,在用户确认后打印;也可以直接打印

boolean a=job.printDialog();

if(a){

//System.out.println(a);

job.print();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

2.打印中字符串换行

思路:按像素来判断是否要换行,按字符串长度换行的话会有英文和汉子的问题,宽度不一样。

int StrPixelWidth = metrics.stringWidth(str); //字符串长度(像素) str要打印的字符串

int lineSize =(int) Math.ceil(StrPixelWidth*1.0/width);//要多少行

//FontMetrics metrics = new FontMetrics(font) {};

// Rectangle2D bounds = metrics.getStringBounds(str, null);

// int widthInPixels = (int) bounds.getWidth();

//System.out.println(StrPixelWidth+"---:");

if(width < StrPixelWidth){//页面宽度(width)小于 字符串长度

lineNum = (int) Math.ceil(StrPixelWidth*1.0/lineSize);//算出行数

StringBuilder sb =new StringBuilder();//存储每一行的字符串

int j=0;

int tempStart = 0;

String tempStrs[] =new String[lineSize];//存储换行之后每一行的字符串

for(int i1 =0;i1

char ch = str.charAt(i1);

sb.append(ch);

Rectangle2D bounds2 = metrics.getStringBounds(sb.toString(), null);

int tempStrPi1exlWi1dth = (int) bounds2.getWidth();

if(tempStrPi1exlWi1dth > width){

tempStrs[j++] = str.substring(tempStart,i1);

tempStart = i1;

sb.delete(0, sb.length());

sb.append(ch);

}

if(i1 == str.length()-1){//最后一行

tempStrs[j] = str.substring(tempStart);

}

}

非常抱歉,我之前提供的代码存在错误。在 PyTorch 中,并没有直接提供离散余弦变换(DCT)的函数。对于 DCT 的实现,你可以使用 `torch.rfft` 函数结合 DCT 系数矩阵来进行计算。 下面是一个修正后的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim # 定义离散余弦变换(DCT)系数矩阵 dct_matrix = torch.zeros(256, 256) for i in range(256): for j in range(256): dct_matrix[i, j] = torch.cos((2 * i + 1) * j * 3.14159 / (2 * 256)) # 定义 OMP 算法 def omp(A, y, k): m, n = A.shape x = torch.zeros(n, 1) residual = y.clone() support = [] for _ in range(k): projections = torch.abs(A.t().matmul(residual)) index = torch.argmax(projections) support.append(index) AtA_inv = torch.linalg.inv(A[:, support].t().matmul(A[:, support])) x_new = AtA_inv.matmul(A[:, support].t()).matmul(y) residual = y - A[:, support].matmul(x_new) x[support] = x_new return x # 加载原始图像 image = torch.randn(256, 256) # 压缩感知成像 measurement_matrix = torch.fft.fft(torch.eye(256), dim=0).real compressed = measurement_matrix.matmul(image.flatten().unsqueeze(1)) # 使用 OMP 进行重构 reconstructed = omp(dct_matrix, compressed, k=100) # 计算重构误差 mse = nn.MSELoss() reconstruction_error = mse(image, reconstructed.reshape(image.shape)) print("重构误差:", reconstruction_error.item()) ``` 在这个示例中,我们手动定义了 DCT 系数矩阵 `dct_matrix`,然后使用 `torch.fft.fft` 函数计算测量矩阵,并进行实部提取。接下来的步骤与之前的示例相同。 请注意,这只是一个示例,用于演示如何使用自定义的 DCT 系数矩阵进行压缩感知成像。在实际应用中,你可能需要根据具体的需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值