SWT窗口特效之抖動特效

我們在使用QQ的時候,可以通過向好友發送一個窗口抖動,然後就可以看到窗口在不段的跳舞了,呵呵。其實,我們在java中也可以實現這樣的效果,其原理就是不斷的在小範圍內隨機改變窗口的location就可以實現了。代碼如下:

 

final int amplitude = 6; // 抖動的幅度
final long _times = 3 * 1000; // 抖動的時間
final Point location = shell.getLocation(); // 記錄最開始時shell的位置
final long startTime = System.currentTimeMillis();
new Thread() {
    public void run() {
        int startX = location.x - amplitude/2, startY = location.y - amplitude/2;
        while (System.currentTimeMillis() - startTime <= _times) {
            final int rx = RandomUtil.random(startX, startX + amplitude);
            final int ry = RandomUtil.random(startY, startY + amplitude);
            shell.getDisplay().syncExec(new Runnable() {
                public void run() {
                    shell.setLocation(rx, ry);
                }
            });
            Thread.yield();
        }
        // restore the shell's location
        shell.getDisplay().syncExec(new Runnable() {
            public void run() {
                shell.setLocation(location);
            }
        });
    }
}.start();

 

    代碼中抖動的幅度是指以窗口的左上角頂點爲中心左右的偏移距離(取值爲一半),比如一個窗口的location爲(20,30),那麼對於6個像素的振幅,其location可以活動的範圍就是一個矩形[(17,27),(27,23),(17,33),(23,33)]。

 

    其中RandomUtil爲一實用類,來獲取某一個範圍內的隨機數,其代碼如下:

 


public class RandomUtil {
    private static final Random random = new Random();
	
    /**
     * return a integer value between from and to.
     * @param from start value,include
     * @param to end value,exclude
     * @return
     */
    public static int random(int from, int to) {
        return from + random.nextInt(to - from);
    }
}

 

    另外,使用Thread.yield()和Thread.sleep(interval)是不太一樣的,前者是交出CPU運行時間,但並不表示下一個CPU時間就不是分配給該線程;而後者則是完全交出CPU運行時間,直到睡眠結束。所以分別實用這兩個來暫停線程所看到的效果將不太一樣,呵呵,具體是什麼樣的效果,大家自己試試吧:-)

發佈了41 篇原創文章 · 獲贊 68 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章