自定义 view 练手 - 简单的饼状图
2018-10-30 本文已影响49人
前行的乌龟
ps:本项目参考自:安卓自定义View进阶-Canvas之绘制图形
今天咱们来一个例子练练手,饼状图这样的图表算是最好的了,复杂的话可以很复杂, 采用 surfaceview + 动画 可以使用很优秀的观感体验;简单的话可以很简单,仅仅画出图来就行,不用考虑动画啥的
今天咱们就来画个简单的,毕竟饭总是要一口一口的吃不是,别看简单, 写出来熟练了,这就是在真正夯实我们自定义 view 的基础,基础熟练了,再学复杂的就一马平川了,会很快的~
效果图:
项目地址:BW_Libs
项目思路
这个不用说吧,大家聪明的脑袋都能反应过来,是用弧线来完成的。画弧线时链接中心点就能实现这个效果了,计算总得数值,根据每块的数值占全部数值的百分比,再 * 360 得到每块的弧度,就能画出这个饼状图了
代码很简单,我就不做过多解释了,大伙直接看代码吧
activity:
class PieViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pie_view)
view_pieview.post {
var data = mutableListOf<Float>()
data.add(100f)
data.add(200f)
data.add(200f)
data.add(300f)
data.add(300f)
data.add(300f)
data.add(200f)
data.add(200f)
data.add(300f)
data.add(200f)
view_pieview.setData(data)
}
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bloodcrown.bw.PieViewActivity">
<com.bloodcrown.bw.pieview.PieView
android:id="@+id/view_pieview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
PieView :
class PieView : View {
private var mPaint: Paint = Paint()
var startAngle: Float = 0f
var mData = mutableListOf<Float>()
var mColor = mutableListOf(0xffccff00, 0xFFCCFF00, 0xFF6495ED, 0xFFE32636, 0xFF800000, 0xFF808000, 0xFFFF8C69, 0xFF808080,
0xFFE6B800, 0xFF7CFC00)
@JvmOverloads
constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0)
: super(context, attributeSet, defAttrStyle) {
// 初始化画笔
initPaint()
}
fun initPaint() {
mPaint.strokeWidth = 0f
mPaint.color = Color.BLACK
mPaint.isAntiAlias = true
mPaint.style = Paint.Style.FILL
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (mData.size == 0) return
canvas?.translate(width / 2.toFloat(), height / 2.toFloat())
// 饼状图半径
val r = (Math.min(width, height) / 2 * 0.8).toFloat()
val rect = RectF(-r, -r, r, r)
var currentAngle: Float = startAngle
for ((index, value) in mData.withIndex()) {
mPaint.color = mColor.get(index).toInt()
if (index == mData.size - 1) {
canvas?.drawArc(rect, currentAngle, startAngle + 360 - currentAngle, true, mPaint)
return
}
canvas?.drawArc(rect, currentAngle, 360 * value, true, mPaint)
currentAngle += 360 * value
}
}
fun setData(data: MutableList<Float>?) {
mData.clear()
var total: Float = 0f
data?.forEach { total += it }
data?.forEach { mData.add(it / total) }
postInvalidate()
}
}