在Canvas上绘制可修改的图片

2007-12-23 10:35:42  作者

/*--------------------------------------------------
*MutableImage.Java
*
*Drawmutableimageonacanvas
*
*Examplefromthebook:CoreJ2METechnology
*CopyrightJohnW.MUChowhttp://www.CoreJ2ME.com
*Youmayuse/modifyforanynon-commercialpurpose
*-------------------------------------------------*/
importjavax.microedition.midlet.*;
importjavax.microedition.lcdui.*;

publicclassMutableImageWithCanvasextendsMIDlet
{
privateDisplaydisplay;//Thedisplay
privateImageCanvascanvas;//Canvas
publicMutableImageWithCanvas()
{
display=Display.getDisplay(this);
canvas=newImageCanvas(this);
}
protectedvoidstartApp()
{
display.setCurrent(canvas);
}
protectedvoidpauseApp()
{}

protectedvoiddestroyApp(booleanunconditional)
{}
publicvoidexitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
}

/*--------------------------------------------------
*ClassImageCanvas
*
*Drawmutableimage
*-------------------------------------------------*/
classImageCanvasextendsCanvasimplementsCommandListener
{
privateCommandcmExit;//Exitmidlet
privateMutableImagemidlet;
privateImageim=null;
privateStringmessage="CoreJ2ME";
publicImageCanvas(MutableImagemidlet)
{
this.midlet=midlet;
//Createexitcommand%26amp;listenforevents
cmExit=newCommand("Exit",Command.EXIT,1);
addCommand(cmExit);
setCommandListener(this);

try
{
//Createmutableimage
im=Image.createImage(80,20);

//Getgraphicsobjecttodrawontotheimage
Graphicsgraphics=im.getGraphics();

//Specifyafontface,styleandsize
Fontfont=Font.getFont(Font.FACE_SYSTEM,Font.STYLE_PLAIN,Font.SIZE_MEDIUM);
graphics.setFont(font);

//Drawafilled(black)rectangle
graphics.setColor(0,0,0);
graphics.fillRoundRect(0,0,im.getWidth()-1,im.getHeight()-1,20,20);
//Centertexthorizontallyintheimage.Drawtextinwhite
graphics.setColor(255,255,255);
graphics.drawString(message,
(im.getWidth()/2)-(font.stringWidth(message)/2),0,
Graphics.TOPGraphics.LEFT);
}
catch(Exceptione)
{
System.err.println("Errorduringimagecreation");
}
}

/*--------------------------------------------------
*Drawmutableimage
*-------------------------------------------------*/
protectedvoidpaint(Graphicsg)
{
//Centertheimageonthedisplay
if(im!=null)g.drawImage(im,getWidth()/2,getHeight()/2,Graphics.VCENTERGraphics.HCENTER);
}

publicvoidcommandAction(Commandc,Displayabled)
{
if(c==cmExit)
midlet.exitMIDlet();
}
}

(出处http://www.knowsky.com)