Dynamic text in live wallpaper

Welcome. I have a problem. I want to make dynamic wallpapers to change text every few seconds. The program works very well because the text is changing, but changing so that the previous text is still displayed, and after a few seconds I have a lot of text. I searched everywhere, but I'm new and don’t know how to solve this problem. There is a code:

private class MyWallpaperEngine extends Engine { private final Handler handler = new Handler(); private final Runnable drawRunner = new Runnable() { @Override public void run() { draw(); } }; private Paint paint = new Paint(); private int width; int height; private boolean visible = true; public MyWallpaperEngine() { paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.WHITE); handler.post(drawRunner); } @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); } @Override public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { this.width = width; this.height = height; super.onSurfaceChanged(holder, format, width, height); } private void draw() { SurfaceHolder holder = getSurfaceHolder(); Canvas canvas = null; try { canvas = holder.lockCanvas(); if (canvas != null) drawAnimation(canvas); } finally { if (canvas != null) holder.unlockCanvasAndPost(canvas); } if (visible) { handler.postDelayed(drawRunner, 4000); } } private void drawAnimation(Canvas c){ Random r = new Random(); int i1=r.nextInt(200-50) + 50; String text = Integer.toString(i1); c.drawText(text, i1, i1, paint); } } 
+4
source share
1 answer

You should clear the canvas before drawing using something like

 c.drawColor(int color); 

or draw everything that covers the entire area, otherwise you just draw what was already on the canvas.

+2
source

Source: https://habr.com/ru/post/1398834/


All Articles