问题
It is possible to draw from one Graphics2D
to another Graphics2D
?
Let me explain.
I have printing issues, when i display a JTextArea
or JTextPanel
in screen, internaly its used sun.java2d.SunGraphics2D
, but when im printing its used sun.print.PeekGraphics
and sun.awt.windows.WPathGraphics
.
The problem is with some kind of Fonts, like Arial. In some sizes lines are cut.
I have tryed a lot of ways to render the text in printing, Graphics2D.drawString
, SwingUtilities2.drawString
, TextLayout.drawString
, but in some cases lines are still cut, or lines are not cut but some kind of justification makes disapear white spaces.
So my idea is try to render components with sun.java2d.SunGraphics2D and "copy" the surface to the printer via sun.print.PeekGraphics
or sun.awt.windows.WPathGraphics
.
Thanks in advance.
回答1:
Yes its possible, thats how double buffering is achieved in a lot of Java Games. What you need is the Graphics2D's drawImage() method which takes in another Graphics2D object to draw in. E.g. from a small game of mine:
private Main(){
...
/* Create the backbuffer as a BufferedImage object */
this.doubleBuffer = new BufferedImage(this.WIDTH, this.HEIGHT, BufferedImage.TYPE_INT_RGB);
/* create a Graphics 2D object to draw INTO this backbuffer */
this.doubleBufferG2D = (Graphics2D) doubleBuffer.createGraphics();
...
}
Somewhere else:
/*Now lets draw the backbuffer INTO the screen */
g2d.drawImage(doubleBuffer, null , 0, 0);
Edit: heh I realized its not exactly as above...lemme think on it.
Edit2: Alright the above can still be used a sample, but the sequence of steps to draw from one Graphics2D to another should be as such: 1. From a Graphics2D object to an Image/BufferedImage object using drawGraphics(). 2. From the Image/BufferedImage above, extract its member Graphics2D object by using itscreateGraphics().
回答2:
Looks like you can do one of two things:
create a Graphics2D on an image, do your rendering, then draw the image into another Graphics2D
or create Graphics2D from original Graphics2D using Graphics.create() methods and then do you rendering.
来源:https://stackoverflow.com/questions/18315716/draw-graphics2d-to-another-graphics2d