1. 程式人生 > >[Android例項] 波浪動畫效果,正弦曲線繪製

[Android例項] 波浪動畫效果,正弦曲線繪製

我們都知道正弦曲線的表示式為y=Asin(ωx+φ)+k,所以,在該demo中,我自定義一個view,在view的onDraw函式裡手動繪製波浪效果的正弦函式,根據x座標和正弦曲線表示式獲取y座標,此時y=10 * Math.sin((i + angle) * Math.PI / 180) + 20;

主要程式碼:

@Override
    public void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int
height = getHeight(); int width = getWidth(); paint1.setColor(Color.rgb(205, 243, 246)); paint2.setAlpha(200); paint2.setColor(Color.rgb(150, 206, 231)); paint3.setAlpha(150); paint3.setColor(Color.rgb(89, 186, 231)); double lineX = 0; double lineY1 = 0
; double lineY2 = 0; double lineY3 = 0; for (int i = 0; i < width; i++) { lineX = i; if (isRun) { lineY1 = Math.sin((i + angle) * Math.PI / 180); lineY2 = 10 * Math.sin((i + angle) * Math.PI / 180) + 20; lineY3 = 20
* Math.sin((i + angle) * Math.PI / 180) + 50; } else { lineY1 = 0; lineY2 = 20; lineY3 = 50; } canvas.drawLine((int) lineX, (int) (lineY1 + height / 1.5), (int) lineX + 1, (int) (lineY2 + height / 1.5), paint1); canvas.drawLine((int) lineX, (int) (lineY2 + height / 1.5), (int) lineX + 1, (int) (lineY3 + height / 1.5), paint2); canvas.drawLine((int) lineX, (int) (lineY3 + height / 1.5), (int) lineX + 1, height, paint3); } }

開啟執行緒進行每隔1毫毛angle+1,當angle為360的時候,設定angle為0:

@Override
    public void run() {
        // TODO Auto-generated method stub
        while (isRun) {
            angle++;
            if (angle == 360) {
                angle = 0;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void start() {
        isRun = true;
        new Thread(this).start();
    }

    public void stop() {
        isRun = false;
        angle = 0;
    }

這裡寫圖片描述 這裡寫圖片描述

下載地址:專案程式碼