我正在为 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编程新手,谢谢你帮助我:)
最佳答案
根据您的评论:每次调用 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;
关于java - 具有弹跳效果的动态壁纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158023/