package com.example.administrator.jlj20180412demo.newview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Administrator on 2018/4/12.
*/
public class MyView extends View{
private Paint paint;
private int[] col;
private int w;
private int h;
private RectF rectF;
private float firstX;
float z = -400;
float s = -400;
float y = 400;
float x = 400;
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);
//实例化一个画笔
paint = new Paint();
//给画笔上颜色
paint.setColor(Color.RED);
/**
* 可以弄个色盘,使用for循环给画笔上颜色
*/
col = new int[]{Color.LTGRAY, Color.BLUE, Color.RED, Color.GREEN, Color.MAGENTA, Color.WHITE};
//矩形
rectF = new RectF(z, s, y, x);
}
/**
* 取到宽高,点一个自定义view的中心点
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
w = width / 2;
h = height / 2;
}
/**
* 搞起来,画
*
* @param canvas
*/
int d = 60;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(w, h);//把当前画布的原点移到 位置变换
canvas.rotate(d);//旋转角度,用于控制角度位置
drawCircleWithColor(canvas);//用色彩画圆
}
int starteangle = 0;
private void drawCircleWithColor(Canvas canvas) {
for (int i = 0; i < col.length; i++) {
paint.setColor(col[i]);
canvas.drawArc(rectF, starteangle, 360 / col.length, true, paint);
starteangle += 360 / col.length;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN://按下
float lastX;
firstX = lastX = event.getX();
break;
case MotionEvent.ACTION_MOVE://移动
w = (int) event.getX();
h = (int) event.getY();
invalidate();
break;
case MotionEvent.ACTION_UP:// 抬起
lastX = event.getX();
if (lastX - firstX == 0) {
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
d += 1;
postInvalidate();
}
};
timer.schedule(timerTask, 0, 1);
} else {
//发生了拖拽
}
break;
}
return true;
}
}