废话不多说,直接上代码
public class CricleView extends View {
/**
* 第一圈的颜色
*/
private int mFirstColor;
/**
* 第二圈的颜色
*/
private int mSecondColor;
/**
* 圈的宽度
*/
private int mCircleWidth;
/**
* 画笔
*/
private Paint mPaint;
/**
* 当前进度
*/
private int mProgress;
/**
* 速度
*/
private int mSpeed;
/**
* 是否应该开始下一个
*/
private boolean isNext = false;
public CricleView(Context context) {
this(context, null);
}
public CricleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CricleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CricleView, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.CricleView_firstColor:
mFirstColor = a.getColor(attr, Color.GREEN);
break;
case R.styleable.CricleView_secondColor:
mSecondColor = a.getColor(attr, Color.RED);
break;
case R.styleable.CricleView_circleWidth:
mCircleWidth = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics()));
break;
case R.styleable.CricleView_speed:
mSpeed = a.getInt(attr, 20);// 默认20
break;
}
}
a.recycle();
mPaint = new Paint();
// 绘图线程
new Thread()
{
public void run()
{
while (true)
{
mProgress++;
if (mProgress == 360)
{
mProgress = 0;
if (!isNext)
isNext = true;
else
isNext = false;
}
postInvalidate();
try
{
Thread.sleep(mSpeed);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
}.start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centre = getWidth() / 2; // 获取圆心的x坐标
int radius = centre - mCircleWidth / 2;// 半径
mPaint.setStrokeWidth(mCircleWidth); // 设置圆环的宽度
mPaint.setAntiAlias(true); // 消除锯齿
mPaint.setStyle(Paint.Style.STROKE); // 设置空心
RectF oval = new RectF(centre - radius, centre - radius, centre + radius, centre + radius); // 用于定义的圆弧的形状和大小的界限
if (!isNext)
{// 第一颜色的圈完整,第二颜色跑
mPaint.setColor(mFirstColor); // 设置圆环的颜色
canvas.drawCircle(centre, centre, radius, mPaint); // 画出圆环
mPaint.setColor(mSecondColor); // 设置圆环的颜色
canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根据进度画圆弧
} else
{
mPaint.setColor(mSecondColor); // 设置圆环的颜色
canvas.drawCircle(centre, centre, radius, mPaint); // 画出圆环
mPaint.setColor(mFirstColor); // 设置圆环的颜色
canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根据进度画圆弧
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
float v = x%y;
this.invalidate();
return true;
}
}
在values下创建一个文件,内容如下
<resources>
<attr name="firstColor" format="color" />
<attr name="secondColor" format="color" />
<attr name="circleWidth" format="dimension" />
<attr name="speed" format="integer" />
<declare-styleable name="CricleView">
<attr name="firstColor" />
<attr name="secondColor" />
<attr name="circleWidth" />
<attr name="speed" />
</declare-styleable>
</resources>