public class conView extends View implements View.OnClickListener{
private Paint paint;
private Paint paint1;
private Rect rect1;
private RectF rectF;
int countX;
int countY;
private int measuredWidth;
private int measuredHeight;
private int[] cor;
private int[] cor1;
int d=60;
public conView(Context context) {
//super改成this是为了可以调用自身
this(context,null);
}
public conView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public conView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
getinit();
}
//初始化
public void getinit(){}{
setOnClickListener(this);
paint = new Paint();
paint1 = new Paint();
//定义画布颜色
cor1 = new int[]{Color.RED,Color.BLACK,Color.DKGRAY,Color.GREEN,Color.GRAY,Color.MAGENTA,Color.RED,Color.BLACK,Color.DKGRAY,Color.GREEN,Color.GRAY,Color.MAGENTA};
//定义矩形
rectF = new RectF(-200, -200, 200, 200);
}
//获取当前屏幕长和宽
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measuredWidth = getMeasuredWidth();
measuredHeight = getMeasuredHeight();
countX= measuredWidth / 2;
countY= measuredHeight / 2;
}
Canvas canvas;
//制作动画
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas=canvas;
//每次旋转的初始角度
int step=0;
//每次旋转的角度
int pess=360/cor1.length;
// canvas.drawRect(rect1,paint);
//为了可以将图片定义到中心位置
canvas.translate(countX, countY);
//让图片进行旋转
canvas.rotate(d);
//for循环的给画布上颜色
for (int i = 0; i <cor1.length ; i++) {
paint1.setColor(cor1[i]);
canvas.drawArc(rectF,step,pess,true,paint1);
step+=60;
}
}
//事件1分发
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
break;
//鼠标移动时 图画进行旋转
case MotionEvent.ACTION_MOVE:
d+=10;
postInvalidate();
break;
}
return super.onTouchEvent(event);
}
//点击时 图画进行旋转
@Override
public void onClick(View view) {
new Thread(){
// @Override
// public void run() {
// super.run();
// while (true){
// d+=10;
// postInvalidate();
// try {
// sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//
// }
}.start();
//如果想托拽它 进行变动 只需要加上x和 y位置 赋给平移参数 就可以了 因为一开始它在正中央所以获取xy时需要减掉正中央位置 才可以赋给平移现在的xy值
canvas.translate(ww+with,yy+hitg);
ww= event.getX()-with;
yy= event.getY()-hitg;
}}