簡體   English   中英

setBackground() 方法不適用於 Graphics2D object

[英]setBackground() method is not working for Graphics2D object

我需要有關 Graphics2D class 的幫助,我不確定為什么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"));

謝謝你們的時間

您從未填充圖像或繪制任何填充形狀。 設置背景顏色不會改變圖像,它只會選擇將用於下一次填充背景顏色的操作的顏色。 這就像在畫筆上塗漆,但從不在 canvas 上塗漆。 但正如clearRect的文檔所說,您應該使用setColor后跟fillRect

您計算 position 以在屏幕上繪制字符串的方式似乎也存在問題。 您使用stringWidth - width/2 寬度為 128。假設 stringWidth 為 32。那么這將是 32 - 128/2,或 32 - 64,或 -32。 根據字符串的寬度,至少有一部分會被繪制在緩沖圖像之外。 它將被剪裁,要么不可見,要么僅部分可見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM