我需要有關 Graphics2D 類的一些幫助,我不確定為什么setBackground() 方法不起作用,渲染的影像背景只是保持白色。
int width = 128, height = 32;
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
Font font = new Font("TimesRoman", Font.BOLD, 12);
ig2.setBackground(Color.BLACK);
ig2.setFont(font);
String message = "custom text";
FontMetrics fontMetrics = ig2.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();
ig2.setPaint(Color.red);
ig2.drawString(message, stringWidth - width/2, height / 4 stringHeight / 6);
ImageIO.write(bi, "PNG", new File("src/output.jpeg"));
謝謝你們的時間
uj5u.com熱心網友回復:
您從未填充影像或繪制任何填充形狀。設定背景顏色不會改變影像,它只會選擇將用于下一次填充背景顏色的操作的顏色。這就像把顏料涂在畫筆上,但從不在畫布上作畫。但正如clearRect的檔案所說,您應該使用setColor后跟fillRect。
您計算在螢屏上繪制字串的位置的方式似乎也存在問題。你用stringWidth - width/2. 寬度為 128。假設 stringWidth 為 32。那么這將是 32 - 128/2,或 32 - 64,或 -32。根據字串的寬度,至少有一部分會被繪制在緩沖影像之外。它將被剪裁,要么不可見,要么僅部分可見。
我會建議width/2 - stringWidth/2(或只是(width - stringWidth)/2)。這個想法是從影像的中心 width/2 開始,然后備份字串的一半寬度,使其位于影像的中心。雖然,我不知道你打算如何看待結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419553.html
標籤:
下一篇:如何正確更改像素的顏色?
