自定义View风车旋转


import android.util.AttributeSet;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

/**
 * author:Created by niuyuejiao on 2018/4/13.
 */

public class MyView extends View implements View.OnClickListener {

    private Paint paint;
    private RectF rectF;
    private int[] colors;
    private Paint paintA;
    private Rect rect;
    private int centerX;
    private int centerY;
    private int sweepAngle;

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //得到宽和高
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();
        //设置中心点
        centerX = width / 2;
        centerY = height / 2;
    }

    private void initView() {
        setOnClickListener(this);
        //矩形绘画
        paintA = new Paint();
        paintA.setColor(Color.BLACK);
        rect = new Rect(-200, -200, 200, 200);
        //扇形绘画
        paint = new Paint();
        // paint.setColor(Color.RED);
        rectF = new RectF(-200, -200, 200, 200);
        colors = new int[]{Color.RED, Color.WHITE, Color.GREEN, Color.DKGRAY, Color.YELLOW};
        sweepAngle = 360 / colors.length;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int startAngle = 0;
        //将画布位移到中心点
        canvas.translate(centerX, centerY);
        canvas.drawRect(rect, paintA);
        //旋转
        canvas.rotate(d);
        //遍历颜色的长度
        for (int i = 0; i < colors.length; i++) {
            int color = colors[i];
            paint.setColor(color);
            canvas.drawArc(rectF, startAngle, sweepAngle, true, paint);
            startAngle += sweepAngle;
        }
    }

    int d=60;
    @Override
    public void onClick(View view) {
        Timer timer = new Timer();
        TimerTask task=new TimerTask() {
            @Override
            public void run() {
                d++;
                //刷新
                postInvalidate();
            }
        };
        timer.schedule(task,2000,50);
    }
}

你可能感兴趣的:(自定义View风车旋转)