这个圆环是静态的,没有自动增加的动画
绘制并不复杂,有些细节点容易搞错,这里写出来,算是做个笔记。
先放出源码,细节点,后面会说明。建议看后面的说明。最后,会进行扩展,绘制扇形
需求/功能说明:
1、假设一个班级里有 X 个人,班级里的学习有的篮球、有的足球、有的书法、有的绘画,还有的,什么都没学
2、圆环绘制的起点,是圆环顶部,逆时针依次绘制
效果图:
代码:
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.view.View
class MyView : View {
private var mContext: Context? = null
private var vW: Int = 0
private var vH: Int = 0
//半径
private var radius: Float = 0f
//背景圆环画笔
private var bgCirclePaint: Paint? = null
//圆环画笔
private var lanQiuCirclePaint: Paint? = null
private var zuQiuCirclePaint: Paint? = null
private var shuFaCirclePaint: Paint? = null
private var huiHuaCirclePaint: Paint? = null
//文字画笔1
private var textPaint_1: TextPaint? = null
//文字画笔2
private var textPaint_2: TextPaint? = null
//文字1的偏移量
private var textOffset_1: Float = 0f
//文字2的偏移量
private var textOffset_2: Float = 0f
//掌握对应的矩形,用于辅助绘制 掌握 圆环
private var rectF: RectF? = null
constructor(context: Context?) : super(context) {
mContext = context
init()
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
mContext = context
init()
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
mContext = context
init()
}
private fun init() {
//半径。根据布局文件,控件的宽高是 200dp。20是圆环画笔宽度。应该10就够,我这里往回缩了一点
radius = UiUtils.dip2px(mContext, 100f) - 20f
//背景圆画笔
bgCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)
bgCirclePaint?.style = Paint.Style.STROKE
bgCirclePaint?.color = Color.parseColor("#888888")
bgCirclePaint?.strokeWidth = 20f
//篮球圆环画笔
lanQiuCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)
lanQiuCirclePaint?.style = Paint.Style.STROKE
lanQiuCirclePaint?.color = Color.parseColor("#ff0000")
lanQiuCirclePaint?.strokeWidth = 20f
//足球圆环画笔
zuQiuCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)
zuQiuCirclePaint?.style = Paint.Style.STROKE
zuQiuCirclePaint?.color = Color.parseColor("#00ff00")
zuQiuCirclePaint?.strokeWidth = 20f
//书法圆环画笔
shuFaCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)
shuFaCirclePaint?.style = Paint.Style.STROKE
shuFaCirclePaint?.color = Color.parseColor("#0000ff")
shuFaCirclePaint?.strokeWidth = 20f
//绘画画笔。不同于上面,另外一种写法:把一个画笔传进去
huiHuaCirclePaint = Paint(shuFaCirclePaint)
huiHuaCirclePaint?.color = Color.parseColor("#fe7c2b")
//文字画笔1
textPaint_1 = TextPaint(Paint.ANTI_ALIAS_FLAG)
textPaint_1?.setTextSize(UiUtils.dip2px(mContext!!, 13f).toFloat());
textPaint_1?.setColor(Color.parseColor("#888888"));
textPaint_1?.setTextAlign(Paint.Align.CENTER);
textOffset_1 = (textPaint_1!!.ascent() + textPaint_1!!.descent()) / 2
//文字画笔2
textPaint_2 = TextPaint(Paint.ANTI_ALIAS_FLAG)
textPaint_2?.setTextSize(UiUtils.dip2px(mContext!!, 12f).toFloat());