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

本文介绍了一种自定义Android圆盘控件的方法,通过设置不同颜色和角度展示多彩的圆盘样式。代码中详细解释了如何使用XML定义属性及在Java中获取这些属性,并在onDraw方法中绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

先上图,一目了然


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

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

上代码:

<?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.youkuaiyun.com/detail/elinavampire/8175771




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值