Android绘图Path基于LinearGradient线性动画渐变,Kotlin(2)
这篇
Kotlin
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Shader
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatImageView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MyView : AppCompatImageView {
private var mLinearGradient: LinearGradient? = null
private var mPaint: Paint? = null
private var mPath: Path? = null
private var mStartX = 0f
private var mStartY = 0f
private var mEndX = 0f
private var mEndY = 0f
private val DELTA = 3f
constructor(ctx: Context, attributeSet: AttributeSet) : super(ctx, attributeSet) {
mPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
mPaint?.style = Paint.Style.STROKE
mPaint?.strokeWidth = 50f
mPath = Path()
mPath?.moveTo(mStartX, mStartY)
val W = resources.displayMetrics.widthPixels
val H = resources.displayMetrics.heightPixels
val factor = H / W
CoroutineScope(Dispatchers.IO).launch {
while (true) {
delay(5)
mEndX = mEndX + DELTA
mEndY = mEndX * factor//mEndY + DELTA
Log.d("fly", "$mEndX $mEndY")
mPath?.lineTo(mEndX, mEndY)
mLinearGradient =
LinearGradient(
mStartX,
mStartY,
mEndX,
mEndY,
intArrayOf(Color.RED, Color.BLUE, Color.YELLOW),
null,
Shader.TileMode.CLAMP
)
mPaint?.setShader(mLinearGradient)
if (mEndX >= W || mEndY >= H) {
Log.d("fly", "break $mEndX $mEndY $W $H")
break
}
postInvalidate()
}
}
}
override fun onDraw(canvas: Canvas) {
canvas.drawPath(mPath!!, mPaint!!)
}
}