我正在为Android创建一个生活壁纸,“ic_launcher”能够在“击中”屏幕的左/右边缘时反弹。
public class LiveWallpaperService extends WallpaperService
{
int x,y;
public void onCreate()
{
super.onCreate();
}
public void onDestroy()
{
super.onDestroy();
}
public Engine onCreateEngine()
{
return new MyWallpaperEngine();
}
class MyWallpaperEngine extends Engine
{
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}
};
private boolean visible = true;
public Bitmap image1,backgroundImage;
MyWallpaperEngine()
{
image1 = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.pika);
x=130;
y=200;
}
public void onCreate(SurfaceHolder surfaceHolder)
{
super.onCreate(surfaceHolder);
}
@Override
public void onVisibilityChanged(boolean visible)
{
this.visible = visible;
if (visible)
{
handler.post(drawRunner);
}
else
{
handler.removeCallbacks(drawRunner);
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder)
{
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels)
{
draw();
}
void draw()
{
final SurfaceHolder holder = getSurfaceHolder();
int xVelocity = 10;
Canvas c = null;
try
{
c = holder.lockCanvas();
c.drawColor(Color.BLACK);
if (c != null)
{
c.drawBitmap(backgroundImage, 0, 0, null);
c.drawBitmap(image1, x,y, null);
int width=c.getWidth();
x += xVelocity;
if(x>=width)
{xVelocity = -xVelocity;
}
}
}
finally
{
if (c != null)
holder.unlockCanvasAndPost(c);
}
handler.removeCallbacks(drawRunner);
if (visible)
{
handler.postDelayed(drawRunner, 10);
}
}
}
}
ic_launcher在遇到屏幕边缘时不会反弹(它只是向右移动,直到我再也看不到它为止),有人可以帮我解决这个问题吗?我猜问题就在这几行
int width=c.getWidth();
x += xVelocity;
if(x>=width)
{xVelocity = -xVelocity;
}
}
我仍然是Android编程的新手,感谢您帮助我:)
答案 0 :(得分:2)
继续发表评论后:每次拨打draw()
;
移动
int xVelocity = 10;
所以它位于int x,y;
int x,y;
int xVelocity = 10;
int velValue = 10;
int velInvValue = -10;
然后保留一些更好的反码:
if(x >= width)
{
xVelocity = velInvValue;
}
else if(x <= 0)
{
xVelocity = velValue;
}
x += xVelocity;