Android绘图Path基于LinearGradient线性动画渐变,Kotlin(2)

发布于:2024-12-22 ⋅ 阅读:(18) ⋅ 点赞:(0)

Android绘图Path基于LinearGradient线性动画渐变,Kotlin(2)

 

这篇

Android绘图Path基于LinearGradient线性渐变,Kotlin(1)-CSDN博客文章浏览阅读633次,点赞11次,收藏17次。Android SurfaceView简例Android中各的SurfaceView和View有很大的不同,两者应用场景不同。其中,LinearGradient 1,2,3只是修改渲染器的渲染模式,LinearGradient 1为重复(repeat),LinearGradient 2为镜像模式(mirror),Lin_android lineargradient。作者提供了`getPoints`方法和`FloatPoint`类的示例,以及`PaintView`组件在实际应用中的使用。https://blog.csdn.net/zhangphil/article/details/144508262画出的渐变线是静态的,下面实现动态动画的线性渐变:

 

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!!)
    }
}

 

 

 

 


网站公告

今日签到

点亮在社区的每一天
去签到