这段时间研究了下path动画,简单的写了个demo,废话不多说,直接上代码,相信有基础的程序猿都能看懂,效果如最下面的图片,简单的画一个三角形,画完每条边停顿一下
package leon.com.pathanimationtest import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View /** * Created by leon on 2018/6/21. */ class SelfView : View { var mPaint: Paint = Paint() var length1: Float = 0.0f var length2: Float = 0.0f var length3: Float = 0.0f private var oom: Float = 0.0f lateinit var animatorLine1: ObjectAnimator lateinit var animatorLine2: ObjectAnimator lateinit var animatorLine3: ObjectAnimator lateinit var mPath: Path constructor(context: Context) : super(context) { initPaint() } constructor(context: Context, mAttributeSet: AttributeSet) : super(context, mAttributeSet) { initPaint() } constructor(context: Context, mAttributeSet: AttributeSet, defStyleAttr: Int) : super(context, mAttributeSet, defStyleAttr) { initPaint() } private fun initPaint() { mPaint.color = Color.BLACK mPaint.isAntiAlias = true mPaint.strokeWidth = 10f mPaint.style = Paint.Style.STROKE //一定要设置为画线条 } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val widthSpecSize = View.MeasureSpec.getSize(widthMeasureSpec) val heightSpecSize = View.MeasureSpec.getSize(heightMeasureSpec) val mLayoutSize = Math.min(widthSpecSize, heightSpecSize) setMeasuredDimension(mLayoutSize, mLayoutSize) } fun setData() { prepareDraw() animatorLine1 = ObjectAnimator.ofFloat(this, "percentage", 0.0f, length1 / length3) animatorLine1.duration = 1000 animatorLine2 = ObjectAnimator.ofFloat(this, "percentage", length1 / length3, length2 / length3) animatorLine2.duration = 1000 //animatorLine2.start() animatorLine3 = ObjectAnimator.ofFloat(this, "percentage", length2 / length3, 1.0f) animatorLine3.duration = 1000 //animatorLine3.start() var animationSet = AnimatorSet() animationSet.playSequentially(animatorLine1, animatorLine2, animatorLine3) // animatorLine1.start() animatorLine2.startDelay = 1200 animatorLine3.startDelay = 2400 animatorLine1.start() animatorLine2.start() animatorLine3.start() } private fun prepareDraw() { mPath = Path() mPath.moveTo(100f, 100f) //定位path的起点 mPath.lineTo(100f, 400f) val measure = PathMeasure(mPath, false) length1 = measure.length mPath.lineTo(200f, 100f) val measure2 = PathMeasure(mPath, false) length2 = measure2.length mPath.lineTo(95f, 100f) //path.close() val measure3 = PathMeasure(mPath, false) length3 = measure3.length } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) var totalLength: FloatArray = floatArrayOf(length3, length3) var effect = DashPathEffect(totalLength, (1.0f - oom) * length3) mPaint.pathEffect = effect canvas?.drawPath(mPath, mPaint) } fun setPercentage(progress: Float) { oom = progress invalidate() } }