Android实现在屏幕上移动图片的方法
本文实例讲述了Android实现在屏幕上移动图片的方法。分享给大家供大家参考。具体实现方法如下:
1.Speed.java文件:
packagenet.obviam.droidz.model.components;
publicclassSpeed{
publicstaticfinalintDIRECTION_RIGHT=1;
publicstaticfinalintDIRECTION_LEFT=-1;
publicstaticfinalintDIRECTION_UP=-1;
publicstaticfinalintDIRECTION_DOWN=1;
privatefloatxv=1;//velocityvalueontheXaxis
privatefloatyv=1;//velocityvalueontheYaxis
privateintxDirection=DIRECTION_RIGHT;
privateintyDirection=DIRECTION_DOWN;
publicSpeed(){
this.xv=1;
this.yv=1;
}
publicSpeed(floatxv,floatyv){
this.xv=xv;
this.yv=yv;
}
publicfloatgetXv(){
returnxv;
}
publicvoidsetXv(floatxv){
this.xv=xv;
}
publicfloatgetYv(){
returnyv;
}
publicvoidsetYv(floatyv){
this.yv=yv;
}
publicintgetxDirection(){
returnxDirection;
}
publicvoidsetxDirection(intxDirection){
this.xDirection=xDirection;
}
publicintgetyDirection(){
returnyDirection;
}
publicvoidsetyDirection(intyDirection){
this.yDirection=yDirection;
}
//changesthedirectionontheXaxis
publicvoidtoggleXDirection(){
xDirection=xDirection*-1;
}
//changesthedirectionontheYaxis
publicvoidtoggleYDirection(){
yDirection=yDirection*-1;
}
}
2.main.java文件:
publicvoidrun(){
Canvascanvas;
Log.d(TAG,"Startinggameloop");
while(running){
canvas=null;
//trylockingthecanvasforexclusivepixelediting
//inthesurface
try{
canvas=this.surfaceHolder.lockCanvas();
synchronized(surfaceHolder){
//updategamestate
this.gamePanel.update();
//renderstatetothescreen
//drawsthecanvasonthepanel
this.gamePanel.render(canvas);
}
}finally{
//incaseofanexceptionthesurfaceisnotleftin
//aninconsistentstate
if(canvas!=null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}//endfinally
}
}
publicvoidupdate(){
//checkcollisionwithrightwallifheadingright
if(droid.getSpeed().getxDirection()==Speed.DIRECTION_RIGHT
&&droid.getX()+droid.getBitmap().getWidth()/2>=getWidth()){
droid.getSpeed().toggleXDirection();
}
//checkcollisionwithleftwallifheadingleft
if(droid.getSpeed().getxDirection()==Speed.DIRECTION_LEFT
&&droid.getX()-droid.getBitmap().getWidth()/2<=0){
droid.getSpeed().toggleXDirection();
}
//checkcollisionwithbottomwallifheadingdown
if(droid.getSpeed().getyDirection()==Speed.DIRECTION_DOWN
&&droid.getY()+droid.getBitmap().getHeight()/2>=getHeight()){
droid.getSpeed().toggleYDirection();
}
//checkcollisionwithtopwallifheadingup
if(droid.getSpeed().getyDirection()==Speed.DIRECTION_UP
&&droid.getY()-droid.getBitmap().getHeight()/2<=0){
droid.getSpeed().toggleYDirection();
}
//Updatethelonedroid
droid.update();
}
希望本文所述对大家的Android程序设计有所帮助。