Android动态变化渐变背景

一、项目中效果

github.com/qingfeng194...

二、实现

ValueAnimator + LinearGradient + Matrix平移

  • ValueAnimator:循环生成 0~1 的进度值
  • LinearGradient:创建比视图宽 2 倍的渐变,避免流动时出现断层
  • Matrix 平移:通过进度值控制渐变的水平偏移,实现流动效果

三、示例代码

1、自定义view代码(以粉蓝渐变相融流动效果为例)

kotlin 复制代码
package com.voicerobot.lottie.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.annotation.ColorInt
import androidx.core.content.withStyledAttributes
import com.voicerobot.lottie.R

class GradientBackgroundView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    @ColorInt
    private var colorStart: Int = 0xFFFF4FD8.toInt() //粉色
    @ColorInt
    private var colorEnd: Int = 0xFF3D8BFF.toInt()   //蓝色

    private var shader: LinearGradient? = null
    private val shaderMatrix = Matrix()

    private var animator: ValueAnimator? = null

    private var progress: Float = 0f          // 动画进度(0~1)
    private var intensity: Float = 1f         // 动画强度(0~1,0=无动画)
    private var speedPxPerSec: Float = 180f   // 流动速度(px/秒)

    init {
        // 读取自定义属性(可选)
        context.withStyledAttributes(attrs, R.styleable.GradientBackgroundView) {
            intensity = getFloat(R.styleable.GradientBackgroundView_gbvIntensity, 1f)
            speedPxPerSec = getFloat(R.styleable.GradientBackgroundView_gbvSpeedPxPerSec, 180f)
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startAnimIfPossible()
    }

    override fun onDetachedFromWindow() {
        stopAnim()
        super.onDetachedFromWindow()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (w <= 0 || h <= 0) return

        // 创建2倍宽度的渐变(保证流动时无断层)
        val gradientWidth = w * 2f
        shader = LinearGradient(
            0f, 0f,
            gradientWidth, h.toFloat(),
            intArrayOf(colorStart, colorEnd, colorStart), // 首尾同色,循环无断层
            floatArrayOf(0f, 0.5f, 1f),
            Shader.TileMode.CLAMP
        )
        paint.shader = shader
        startAnimIfPossible()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val w = width
        val h = height
        if (w <= 0 || h <= 0) return

        val currentShader = shader ?: return

        // 根据进度平移渐变
        val dx = (w * progress) * intensity
        shaderMatrix.reset()
        shaderMatrix.setTranslate(dx, 0f)
        currentShader.setLocalMatrix(shaderMatrix)

        // 绘制渐变背景
        canvas.drawRect(0f, 0f, w.toFloat(), h.toFloat(), paint)
    }

    /** 自定义渐变颜色 */
    fun setColors(@ColorInt startColor: Int, @ColorInt endColor: Int) {
        colorStart = startColor
        colorEnd = endColor
        requestLayout()
        invalidate()
    }

    /** 设置动画强度(0=静止,1=最大流动) */
    fun setIntensity(value: Float) {
        intensity = value.coerceIn(0f, 1f)
        invalidate()
    }

    /** 设置流动速度(px/秒) */
    fun setSpeedPxPerSec(value: Float) {
        speedPxPerSec = value.coerceAtLeast(10f)
        restartAnim()
    }

    private fun startAnimIfPossible() {
        if (width <= 0 || height <= 0) return
        if (animator?.isStarted == true) return

        // 根据视图宽度和速度计算动画时长
        val w = width.coerceAtLeast(1)
        val durationMs = ((w / speedPxPerSec) * 1000f).toLong().coerceAtLeast(1200L)

        animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = durationMs
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            interpolator = LinearInterpolator()
            addUpdateListener {
                progress = it.animatedValue as Float
                invalidate()
            }
            start()
        }
    }

    private fun restartAnim() {
        stopAnim()
        startAnimIfPossible()
    }

    private fun stopAnim() {
        animator?.cancel()
        animator = null
    }
}

2、自定义属性

res/values/attrs.xml 中添加自定义属性

xml 复制代码
<resources>
<declare-styleable name="GradientBackgroundView">
<!-- 动画强度(0~1) -->
<attr name="gbvIntensity" format="float" />
<!-- 流动速度(px/秒) -->
<attr name="gbvSpeedPxPerSec" format="float" />
</declare-styleable>
</resources>

四、使用

1、在布局中直接引用

ini 复制代码
<com.voicerobot.lottie.widget.GradientBackgroundView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:gbvIntensity="0.8"
app:gbvSpeedPxPerSec="200" />

2、代码中动态配置

scss 复制代码
// 自定义颜色

gradientView.setColors(0xFF00FF00.toInt(), 0xFFFF0000.toInt())

// 调整动画强度(比如滑动时减弱动画)

gradientView.setIntensity(0.5f)

// 调整流动速度

gradientView.setSpeedPxPerSec(250f)

五、关键细节解析

  1. 2 倍宽度渐变 :创建比视图宽 2 倍的渐变,配合首尾同色(colorStart -> colorEnd -> colorStart),保证流动时无断层。
  2. 动画时长自适应:根据视图宽度和速度(px / 秒)计算动画时长,不同尺寸的视图流动速度一致。
  3. 生命周期管理 :在onAttachedToWindow启动动画、onDetachedFromWindow停止动画,避免内存泄漏。
  4. 性能优化 :仅在视图尺寸变化时重建渐变,动画仅触发invalidate()更新绘制,性能开销极低。
相关推荐
黄林晴7 小时前
Android 17 再曝猛料:通知栏和快捷设置终于分家了,这操作等了十年
android
有位神秘人8 小时前
Android获取设备中本地音频
android·音视频
JMchen1238 小时前
Android网络安全实战:从HTTPS到双向认证
android·经验分享·网络协议·安全·web安全·https·kotlin
CS创新实验室8 小时前
Pandas 3 的新功能
android·ide·pandas
ujainu8 小时前
护眼又美观:Flutter + OpenHarmony 鸿蒙记事本一键切换夜间模式(四)
android·flutter·harmonyos
三少爷的鞋8 小时前
为什么我不在 Android ViewModel 中直接处理异常?
android
草莓熊Lotso9 小时前
Linux 文件描述符与重定向实战:从原理到 minishell 实现
android·linux·运维·服务器·数据库·c++·人工智能
恋猫de小郭9 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
工程师老罗16 小时前
如何在Android工程中配置NDK版本
android
Libraeking19 小时前
破壁行动:在旧项目中丝滑嵌入 Compose(混合开发实战)
android·经验分享·android jetpack