2016-06-09 49 views
1

問題在標題中。例如,如何在下面的代碼片段中將g保存在文件中?有沒有辦法在沒有截圖的情況下在Codename One中保存Graphics對象?

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 ? 

} 

爲什麼我不想截取屏幕截圖是因爲我想保留g的完整分辨率(例如:2000 x 1500)。

我會非常感謝任何能告訴我如何使用Codename來做到這一點的人。如果不可能,那麼知道它就已經很好了!

乾杯,

回答

2

你可以做的是創建一個圖像作爲緩衝區,從圖像中獲取圖形對象,並做所有的圖形操作。然後整個圖像繪製到顯示器並把它保存爲一個文件:

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); 

請注意,我沒有測試它,但它應該工作那樣。

+0

謝謝,這是預期的工作!輸出圖像文件具有與原始圖像相同的尺寸!但爲什麼我使用的方法不起作用?與你唯一的區別是,你使用中間圖像作爲緩衝區,而我直接畫在圖形對象克。在此先感謝您或者@Shai可以添加一些解釋。 – HelloWorld

1

圖形僅僅是一個代理到表面,它沒有任何知識或訪問底層的表面,它是繪畫和其中的原因很簡單。它可以繪製到物理上沒有底層圖像的硬件加速「表面」。

在iOS和Android上,「屏幕」本地繪製且沒有緩衝區的情況都是如此。

+0

謝謝@Shai,所以如果沒有緩衝區,將無法將圖形保存在文件中。因此,截圖是我唯一的出路! – HelloWorld

相關問題