动态画圆(类似可实现绘制其他图形)

1、效果图

动态画圆(类似可实现绘制其他图形)_第1张图片


2、自定义view实现
class DynamicDrawView(context: Context) : View(context) {
    private val mPath: Path = Path()
    private val mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var mPathMeasure: PathMeasure = PathMeasure()
    private var mAnimatorValue: Float = 0.toFloat()
    private val mDstPath: Path = Path()
    private var mLength: Float = 0.toFloat()

    init {
        mPaint.color = Color.RED
        mPaint.style = Paint.Style.STROKE
        mPaint.isAntiAlias = true
        mPaint.strokeWidth = 2F

        mPath.addCircle(Util.Div(900).toFloat(), Util.Div(400).toFloat(), Util.Div(100).toFloat(), Path.Direction.CW) //CW顺时针
        // PathMeasure类似一个计算器,初始化PathMeasure后,可以通过PathMeasure.setPath()的方式来将Path和PathMeasure进行绑定
        mPathMeasure.setPath(mPath, true)
        mLength = mPathMeasure.length

        val mValueAnimator = ValueAnimator.ofFloat(0F, 1F)
        mValueAnimator.addUpdateListener { valueAnimator ->
            mAnimatorValue = valueAnimator.animatedValue as Float
            invalidate()
        }
        mValueAnimator.duration = 8000
        mValueAnimator.repeatCount = ValueAnimator.INFINITE
        mValueAnimator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //动态绘制
        val stop = mLength * mAnimatorValue
        val start = 0
        mPathMeasure.getSegment(start.toFloat(), stop, mDstPath, true) //用于截取整个Path的片段
        canvas.drawPath(mDstPath, mPaint)
    }
}
使用:
   DynamicDrawView dynamicDrawView= new DynamicDrawView(getApplicationContext());
   frameLayout.addView(dynamicDrawView);



你可能感兴趣的:(kotlin)