本文介紹如何將手機屏幕的內(nèi)容存儲為Image對象,這里認為手機屏幕上顯示的是一個Canvas。完成這一個功能的思想就是使用緩沖機制。我們不能直接獲得Canvas上的像素,因此不能直接從Canvas上的內(nèi)容獲得Image對象。轉換一下思路,如果把要繪制的Canvas上的內(nèi)容首先繪制到一個Image上,而這個Image并不顯示到屏幕上,只是在繪畫完成后一次性的顯示到屏幕上。有經(jīng)驗的朋友一定聯(lián)想到了雙緩沖機制,不過這里并不是要使用雙緩沖解決閃屏的問題,而是要得到當前Canvas的內(nèi)容。
下面我們編寫一個簡單的Canvas類來測試一下這個想法,SimpleCanvas是Canvas的子類,為了保存Canvas的內(nèi)容,我們創(chuàng)建一個Image,大小與Canvas的尺寸相當。
class SimpleCanvas extends Canvas{
    
    int w;
    int h;
    PRivate Image offImage = null;
    private boolean buffered = true;
    public SimpleCanvas(boolean _buffered){
        buffered = _buffered;
        w = getWidth();
        h = getHeight();
        if(buffered)
            offImage = Image.createImage(w,h);
    }
    protected void paint(Graphics g) {
        
        int color = g.getColor();
        g.setColor(0xFFFFFF);
        g.fillRect(0,0,w,h);
        g.setColor(color);
        
        Graphics save = g;
        if(offImage != null)
            g = offImage.getGraphics();
        //draw the offimage
        g.setColor(128,128,0);
        g.fillRoundRect((w-100)/2,(h-60)/2,100,60,5,3);
        //draw the offimage to the canvas
        save.drawImage(offImage,0,0,Graphics.TOPGraphics.LEFT);
        
    }
    
    public Image printMe(){
        return offImage;
    }
可以看到paint()方法,并不是直接對Canvas操作,而是先把要畫的內(nèi)容繪制到一個Image上,然后再繪制到Canvas上。這樣到你想抓取屏幕內(nèi)容的時候就可以調用printMe()方法了,返回offImage。編寫一個MIDlet測試一下這個效果。
package com.j2medev;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
 *
 * @author  mingjava
 * @version
 */
public class PrintScreen extends MIDlet implements CommandListener{
    
    private Display display = null;
    private SimpleCanvas canvas = new SimpleCanvas(true);
    private Command printCommand = new Command("Print",Command.OK,1);
    
    public void startApp() {
        if(display == null)
            display = Display.getDisplay(this);
        canvas.addCommand(printCommand);
        canvas.setCommandListener(this);
        display.setCurrent(canvas);
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
    
    public void commandAction(Command command, Displayable displayable) {
        if(command == printCommand){
            Form form = new Form("screen");
            form.append(canvas.printMe());
            display.setCurrent(form);
        }
    }
}
            運行PrintScreen,選擇Print,即可把當前的屏幕顯示到一個Form中。如下圖所示:

(出處:http://m.survivalescaperooms.com)
新聞熱點
疑難解答