Android自己定义(三)实现圆盘的百分比设置

近期一直在学习自己定义控件,昨天看到群里有人问怎样怎样实现圆盘样式的显示,学有所用,于是乎就有了这篇博客

先上图,一目了然


这里的显示颜色以及颜色块的大小你都能够自己设置

这里设置了三种颜色,相应三种颜色的三个角度

上代码:

<?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"/>

这里须要注意的是custom,这就是你自己定义的属性了,前面要声明一下xmlns:custom="http://schemas.android.com/apk/res/你自己的包名"


差点儿相同就这样啦,就实现了你想要的功能,当你看不懂别人的代码逻辑时,你能够debug,这也是一个非常好地办法


代码下载地址:http://download.csdn.net/detail/elinavampire/8175771




posted @ 2017-07-30 20:38  yfceshi  阅读(755)  评论(0编辑  收藏  举报