服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

j2me中使用缓存将屏幕内容存储为image

本文介绍如何将手机屏幕的内容存储为image对象,这里认为手机屏幕上显示的是一个canvas。完成这一个功能的思想就是使用缓冲机制。我们不能直接获得canvas上的像素,因此不能直接从canvas上的内容获得image对象。转换一下思路,如果把要绘制的canvas上的内容首先绘制到一个image上,而这个image并不显示到屏幕上,只是在绘画完成后一次性的显示到屏幕上。有经验的朋友一定联想到了双缓冲机制,不过这里并不是要使用双缓冲解决闪屏的问题,而是要得到当前canvas的内容。

下面我们编写一个简单的canvas类来测试一下这个想法,simplecanvas是canvas的子类,为了保存canvas的内容,我们创建一个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.top|graphics.left); 
 } 
 public image printme(){ 
  return offimage; 
 }

可以看到paint()方法,并不是直接对canvas操作,而是先把要画的内容绘制到一个image上,然后再绘制到canvas上。这样到你想抓取屏幕内容的时候就可以调用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中。

扫描关注微信公众号