android – 动态壁纸中的动态文本

欢迎.我有个问题.我想做动态壁纸,这样每隔几秒钟就可以改变文字.该程序运行良好,因为文本正在改变,但更改,以便以前的文本仍然可见,几秒钟后,我有很多文本.我到处看,但我是初学者,不知道如何解决这个问题.有一个代码:

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);
    }
}  

最佳答案 您应该在绘图之前清除画布,使用类似的东西

c.drawColor(int color);

或绘制覆盖整个区域的任何其他内容,否则您将只绘制画布上已有的内容.

点赞