自定義控件繼承View------Music

這裏寫圖片描述

public class MusicView extends View {

private Paint paint;
private int count;
private float offetx;
private float left;
private float right;

public MusicView(Context context) {
    super(context);
    init();
}

public MusicView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MusicView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private  void init(){

    paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);
    paint.setStrokeWidth(3);

    count = 20;
    offetx = 40;
    left = 20;
    right = 50;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    LinearGradient gradient = new LinearGradient(
            0,
            0,
            left ,
            getHeight(),
            new int[]{Color.RED , Color.GREEN , Color.BLUE},
            null,
            Shader.TileMode.CLAMP
    );

    Log.d("onSizeChanged:  " , "jig: " + getHeight() );
    paint.setShader(gradient);

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    /*
        android 座標系是左上角爲原點 。 詳情見下期的博客 Android 座標系詳解

        這裏我們只需要控制x座標 , 以及右下角的座標。 左上角的y座標控制music的顯示高度
     */
    for(int i = 0; i < count; i++){

        RectF rect = new RectF(left ,
                (float)(Math.random() * 800 + 20),
                right,
                820);
        canvas.drawRect(rect , paint);
        left += offetx;
        right += offetx;
    }

    left -= offetx * count;
    right -= offetx * count;

    this.postInvalidateDelayed(300);
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章