最近一直在学习自定义控件,昨天看到群里有人问如何如何实现圆盘样式的显示,学有所用,于是乎就有了这篇博客
先上图,一目了然
这里的显示颜色以及颜色块的大小你都可以自己设置
这里设置了三种颜色,对应三种颜色的三个角度
上代码:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomCircle">
<attr name="firstColor" format="color"/>
<attr name="secondColor" format="color"/>
<attr name="thirdColor" format="color"/>
<attr name="firstAngle" format="integer"/>
<attr name="secondAngle" format="integer"/>
<attr name="thirdAngle" format="integer"/>
</declare-styleable>
</resources>
以上都属于自定义属性,当然自定义了属性就要给它赋值TypedArray mArray = context.obtainStyledAttributes(attrs, R.styleable.CustomCircle, defStyleAttr, 0); firstColor = mArray.getColor(R.styleable.CustomCircle_firstColor, Color.BLUE); secondColor = mArray.getColor(R.styleable.CustomCircle_secondColor, Color.GREEN); thirdColor = mArray.getColor(R.styleable.CustomCircle_thirdColor, Color.RED); firstAngle=mArray.getInt(R.styleable.CustomCircle_firstAngle, 90); secondAngle=mArray.getInt(R.styleable.CustomCircle_secondAngle, 180); thirdAngle=mArray.getInt(R.styleable.CustomCircle_thirdAngle, 120); mArray.recycle();属性赋值结束后,当然就要开始最重要的部分了,画图,也就是重写onDraw()方法
@Override
protected void onDraw(Canvas canvas) {
int center=getWidth()/2;
int radius=center/2;
mPaint.setColor(Color.GRAY);
mPaint.setStrokeWidth(center);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(center, center, radius, mPaint);
mPaint.setColor(firstColor);
RectF rectF=new RectF(center-radius, center-radius, center+radius, center+radius);
canvas.drawArc(rectF, 0, firstAngle, false, mPaint);
mPaint.setColor(secondColor);
canvas.drawArc(rectF, firstAngle, secondAngle, false, mPaint);
mPaint.setColor(thirdColor);
canvas.drawArc(rectF, secondAngle, thirdAngle, false, mPaint);
}<com.sdufe.thea.guo.view.CustomCircle
android:layout_width="300dp"
android:layout_height="300dp"
custom:firstColor="@android:color/holo_purple"
custom:secondColor="@android:color/holo_blue_bright"
custom:thirdColor="@android:color/holo_orange_light"
custom:firstAngle="60"
custom:secondAngle="180"
custom:thirdAngle="120"/>
差不多就这样啦,就实现了你想要的功能,当你看不懂别人的代码逻辑时,你可以debug,这也是一个很好地办法
代码下载地址:http://download.csdn.net/detail/elinavampire/8175771
原文:http://blog.csdn.net/elinavampire/article/details/41281931