簡體   English   中英

Java從外部paintComponent()將圖形繪制到bufferedImage?

[英]Java drawing shape to bufferedImage from outside paintComponent()?

可能有人問了這個問題,但我需要繪制形狀方面的幫助。 所以我有了Draw類,它擴展了JPanel

我希望能夠從paintComponent();外部繪制一個橢圓形paintComponent(); 方法。 因此,要加載所有圖像,我嘗試將形狀繪制到BufferedImage 但是我沒有合適的Graphics對象。

所以我的問題是:我如何獲得一個適當的Graphics對象以繪制到我的JPanel上,或者如何在paintComponent方法內部繪制並能夠從另一個類調用它?

你從BufferedImage的通過圖形對象getGraphics()或通過Graphics2D對象createGraphics() 然后,通過在其Graphics參數上調用drawImage在paintComponent內繪制圖像。 自創建以來,請在使用完BufferedImage的Graphics對象后再進行處理。 自JVM制作以來,請勿處置傳遞給paintComponent的Graphics對象。

我如何獲得合適的Graphics對象以繪制到我的JPanel上,或者如何在paintComponent方法內部繪制並能夠從另一個類調用它?

你不知道 您永遠不要手動調用任何paint方法。 當組件以這種方式繪制時,背景中發生了很多事情,您無法控制。

如果要“打印”組件,則應使用paintAll

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
componentToBePrinted.printAll(g2d);
g2d.dispose();

一種替代方法是使用BufferedImage並對其進行繪制...

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.BLACK);
g2d.draw(new Rectangle2D.Double(10, 10, 80, 80));
g2d.draw(new Ellipse2D.Double(10, 10, 80, 80));
g2d.dispose();

然后,您可以使用Graphics#drawImage對其進行繪制

暫無
暫無

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

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