Is there a way to save a Graphics object in Codena

2019-06-03 08:31发布

问题:

The question is in the title. For example how can I save g in a file in the following snippet ?

public void paints(Graphics g, Image background, Image watermark, int width, int height) {

g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);

// Upper left corner
g.fillRect(0, 0, 10, 10);

// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);

g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld", 
        (int) (848 ),
        (int) (610)
        );

// NOW how can I save g in a file ?

}

The reaseon why I don't want to take a screenshot is because I want to keep the full resolution of g (eg : 2000 x 1500).

I would be so grateful to anyone that can tell me how to do that with Codename one. If not possible then it is already good to know it!

Cheers,

回答1:

What you could do is to create an Image as buffer, get the graphics object from the image an do all your drawings operations on it. Then draw the whole image to the display and save it as a file:

int height = 2000;
int width = 1500;
float saveQuality = 0.7f;

// Create image as buffer
Image imageBuffer = Image.createImage(width, height, 0xffffff);
// Create graphics out of image object
Graphics imageGraphics  = imageBuffer.getGraphics();

// Do your drawing operations on the graphics from the image
imageGraphics.drawWhaterver(...);

// Draw the complete image on your Graphics object g (the screen I guess) 
g.drawImage(imageBuffer, w, h);

// Save the image with the ImageIO class
OutputStream os = Storage.getInstance().createOutputStream("storagefilename.png");
ImageIO.getImageIO().save(imageBuffer, os, ImageIO.FORMAT_PNG, saveQuality);

Note, that I have not tested it, but it should work like that.



回答2:

Graphics is just a proxy to a surface, it has no knowledge or access to the underlying surface to which it is drawing and the reason for that is quite simple. It can draw to a hardware accelerated "surface" where there is physically no underlying image.

This is the case both on iOS and Android where the "screen" is natively drawn and has no buffer.