自定义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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值