J2ME手机游戏:Canvas类基本绘图实例
public void keyPressed(int keyCode)
{
gameaction=getGameAction(keyCode);
switch(gameaction)
{
//按左、右键选择线条状态
case LEFT:
changeSD=1;
break;
case RIGHT:
changeSD=3;
break;
//按上、下键选择是否填充形状
case UP:
changeFull=0;
break;
case DOWN:
changeFull=1;
break;
}
repaint();
}
public void paint(Graphics g)
{
//设置绘制颜色
g.setColor(0xffffff);
//绘制一个手机全屏幕填充颜色的矩形
g.fillRect(0,0,getWidth(),getHeight());
//设置下列显示画面的颜色
g.setColor(0);
//选择要显示图形是实线(DOLID)或虚线(DOTTED)
if(changeSD==1)
g.setStrokeStyle(Graphics.SOLID);
else
g.setStrokeStyle(Graphics.DOTTED);
//选择要绘制的种类
if(viewType==0)
{
g.drawString("绘制线条", getWidth()/2, 5, Graphics.HCENTER
Graphics.TOP);
//绘制一条直线
g.drawLine(getWidth()/4,100,3×getWidth()/4,100);
}
else if(viewType==1){
g.drawString("绘制矩形", getWidth()/2, 5, Graphics.HCENTER
Graphics.TOP);
if(changeFull==0)
//绘制一个矩形
g.drawRect(getWidth()/4,100,getWidth()/2,40);
else
//绘制一个填充的矩形
g.fillRect(getWidth()/4,100,getWidth()/2,40);
}
else if(viewType==2){
g.drawString("绘制圆角矩形", getWidth()/2, 5, Graphics.HCENTER
Graphics.TOP);
if(changeFull==0)
//绘制一个圆角矩形
g.drawRoundRect(getWidth()/4,100,getWidth()/2,40,30,40);
else
//绘制一个圆角填充矩形
g.fillRoundRect(getWidth()/4,100,getWidth()/2,40,30,40);
}
else if(viewType==3){
g.drawString("绘制弧形", getWidth()/2, 5, Graphics.HCENTER
Graphics.TOP);
if(changeFull==0)
//绘制一个弧形形状
g.drawArc(getWidth()/3,100,40,50,0,150);
else
//绘制一个填充的弧形形状
g.fillArc(getWidth()/3,100,40,50,0,150);
}
else {
//绘制一个填充三角形形状
g.drawString("绘制三角形", getWidth()/2, 5, Graphics.HCENTER
Graphics.TOP);
g.fillTriangle(50,80,80,60,100,120);
}
//依照选择的线条状况
if(viewType!=4)
{
g.drawString("实线", getWidth()/4, 50, Graphics.HCENTER
raphics.TOP);
g.drawString("虚线", 3×getWidth()/4, 50, Graphics.HCENTER
Graphics.TOP);
g.drawImage(handImage, changeSD×getWidth()/4, 60, Graphics.HCENTER
Graphics.TOP);
}