Android View 凡赛尔曲线 气温变化
package com.NS.intelligentvision.customview
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.NS.intelligentvision.R
import com.NS.intelligentvision.bean.baidumap.Forecast
import com.blankj.utilcode.util.SizeUtils
class WeatherCurveView : View {
private var mHeight = 0
private var mWidth = 0
constructor(context: Context?) : super(context) {
init(context, null)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
super(context, attrs, defStyleAttr) {
init(context, attrs)
}
private var paint: Paint? = null
private var textPaint: Paint? = null
fun init(context: Context?, attrs: AttributeSet?) {
paint = Paint()
paint?.textAlign = Paint.Align.CENTER
paint?.isAntiAlias = true
paint?.color = Color.WHITE
paint?.strokeWidth = SizeUtils.dp2px(3f).toFloat()
paint?.style = Paint.Style.STROKE
paint?.textSize = resources.getDimension(R.dimen.size12)
//文字画笔
textPaint = Paint()
textPaint?.textAlign = Paint.Align.CENTER
textPaint?.isAntiAlias = true
textPaint?.color = Color.WHITE
textPaint?.textSize = resources.getDimension(R.dimen.size12)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int)
{
super.onLayout(changed, left, top, right, bottom)
mWidth = width
mHeight = height
}
// var list = arrayListOf(20f, 26f, 21f, 24f, 26f)
private var list: List<Forecast> = arrayListOf()
fun setDataList(data: List<Forecast>?) {
data?.let {
this.list = data
textPointList.clear()
invalidate()
}
}
// var textList = arrayListOf("20",)
private var textPointList = arrayListOf<PointF>()
override fun onDraw(canvas: Canvas) {
if (list.isNullOrEmpty()) {
return
}
textPointList.clear()
var dataAvg = 0f
list.forEach {
dataAvg += it.high
}
dataAvg /= 5
var widthAvg = mWidth / 6f
var controlWidth = mWidth / 6f / 3
var x1 = 0f
var centerY = mHeight / 2f
var y1 = mHeight / 2f
var x2 = 0f
var y2 = y1
var x3 = 0f
var y3 = y1
var path = Path()
path.moveTo(x1, y1)
var bei = resources.getDimension(R.dimen.size15)
for (i in 0 until list.size) {
x1 += controlWidth
//将起始点和结束点的距离分成3分,得4个点(包含起始点和结束点),中间两个点是控制点,第一个控制点y坐标和起始点y坐标相同,第二个控制点y坐标和结束点y坐标相同。
x2 = x1 + controlWidth
y2 = centerY + (dataAvg - list[i].high) * bei
x3 = x2 + controlWidth
y3 = y2
//使用三阶凡赛尔
path.cubicTo(x1, y1, x2, y2, x3, y3)
var textPointY = 0f
//控制文字偏移
if (dataAvg - list[i].high > 0) {
textPointY = y3 + resources.getDimension(R.dimen.size20)
} else {
textPointY = y3 - resources.getDimension(R.dimen.size10)
}
//绘制文字需要的坐标点
textPointList.add(PointF(x3, textPointY))
x1 = x3
y1 = y3
}
x1 += controlWidth
x2 = x1 + controlWidth
y2 = centerY
x3 = x2 + controlWidth
y3 = y2
path.cubicTo(x1, y1, x2, y2, x3, y3)
canvas.drawPath(path, paint!!)
textPointList.forEachIndexed { index, pointF ->
canvas.drawText("${list[index].low}/${list[index].high}°", pointF.x, pointF.y, textPaint!!)
}
}
}