package com.okay.testdemo.ui
import android.content.Context
import android.graphics.*
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.AttributeSet
import android.view.View
import com.okay.testdemo.dp
import kotlin.math.cos
import kotlin.math.sin
/**
* @author : zyl
* @desc :
*/
val RADIUS = 150.dp
val OPEN_ARC = 120
val DASH_WIDTH = 2.dp
val DASH_HEIGHT = 10.dp
val DASH_COUNT = 20
val POINTER_POSITION = 10
val POINT_LENGTH = 120.dp
class DashboardView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
}
private val arcPath = Path()
private val dashPath = Path()
private lateinit var pathDashPathEffect: PathDashPathEffect
init {
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
arcPath.addArc(
width / 2 - RADIUS,
height / 2 - RADIUS,
width / 2 + RADIUS,
height / 2 + RADIUS,
150f,
360f - OPEN_ARC
)
dashPath.addRect(0f, 0f, DASH_WIDTH, DASH_HEIGHT, Path.Direction.CCW)
val pathMeasure = PathMeasure(arcPath, false)
//由于最后一个刻度不够画了 所以计算的时候需要减去一个刻度的宽度
pathDashPathEffect = PathDashPathEffect(
dashPath,
(pathMeasure.length - DASH_WIDTH) / DASH_COUNT,
0f,
PathDashPathEffect.Style.ROTATE
)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
//画弧
canvas.drawPath(arcPath, paint)
//画刻度
paint.pathEffect = pathDashPathEffect
canvas.drawPath(arcPath, paint)
paint.pathEffect = null
//画指针
val angle =
(90 + OPEN_ARC / 2 + (360 - OPEN_ARC) / DASH_COUNT * POINTER_POSITION).toDouble()
canvas.drawLine(
width / 2f,
height / 2f,
width / 2f + (POINT_LENGTH * cos(Math.toRadians(angle))).toFloat(),
height / 2f + (POINT_LENGTH * sin(Math.toRadians(angle))).toFloat(),
paint
)
}
}
网友评论