天天看點

[Android執行個體] 波浪動畫效果,正弦曲線繪制

該篇文章從eoeAndroid搬遷過來的,原文位址:[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(, , ));
        paint2.setAlpha();
        paint2.setColor(Color.rgb(, , ));
        paint3.setAlpha();
        paint3.setColor(Color.rgb(, , ));
        double lineX = ;
        double lineY1 = ;
        double lineY2 = ;
        double lineY3 = ;
        for (int i = ; i < width; i++) {
            lineX = i;
            if (isRun) {
                lineY1 = Math.sin((i + angle) * Math.PI / );
                lineY2 =  * Math.sin((i + angle) * Math.PI / ) + ;
                lineY3 =  * Math.sin((i + angle) * Math.PI / ) + ;
            } else {
                lineY1 = ;
                lineY2 = ;
                lineY3 = ;
            }
            canvas.drawLine((int) lineX, (int) (lineY1 + height / ),
                    (int) lineX + , (int) (lineY2 + height / ), paint1);
            canvas.drawLine((int) lineX, (int) (lineY2 + height / ),
                    (int) lineX + , (int) (lineY3 + height / ), paint2);
            canvas.drawLine((int) lineX, (int) (lineY3 + height / ),
                    (int) lineX + , height, paint3);
        }

    }
           

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

@Override
    public void run() {
        // TODO Auto-generated method stub
        while (isRun) {
            angle++;
            if (angle == ) {
                angle = ;
            }
            try {
                Thread.sleep();
            } 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 = ;
    }
           
[Android執行個體] 波浪動畫效果,正弦曲線繪制
[Android執行個體] 波浪動畫效果,正弦曲線繪制

下載下傳位址:項目代碼