想要实现动态的背景渐变色效果,首先使用linearGradient定义渐变色数组,然后定义属性动画方法并设置合理的动画持续时间,最后使用定时器来合理切换不同的渐变色数组,实现动画变化效果;可以使用Stack组件来将已实现的动态效果设置背景,示例代码如下:
@Entry
@Component
struct Index {
@State bgPositionX: number = 0
@State gradientAngle: number = 135
@State currentColorIndex: number = 0
// 渐变色组(包含多个颜色方案)
colorSchemes: Array<Array<[ResourceColor, number]>> = [
[
['#e0f7ff', 0.0],
['#d9e5ff', 0.2],
['#e6e0ff', 0.4],
['#ffebfa', 0.8],
['#e0f7ff', 1.0]
],
[
['#fff3e6', 0.0],
['#ffe6f0', 0.4],
['#e6ecff', 0.8],
['#f0fff4', 1.0]
],
]
aboutToAppear() {
this.startComplexAnimation()
}
startComplexAnimation() {
// 背景滑动动画
const animateSlide = () => {
animateTo({
duration: 15000,
curve: Curve.EaseInOut
}, () => {
this.bgPositionX = 100
})
animateTo({
duration: 15000,
delay: 15000,
curve: Curve.EaseInOut
}, () => {
this.bgPositionX = 0
})
}
// 渐变角度动画
const animateRotation = () => {
animateTo({
duration: 20000,
curve: Curve.Linear
}, () => {
this.gradientAngle = 495
})
animateTo({
duration: 3000, //动画时长
delay: 1000,
curve: Curve.Linear,
}, () => {
this.gradientAngle = 135
})
}
// 颜色方案切换
setInterval(() => {
this.currentColorIndex = (this.currentColorIndex + 1) % this.colorSchemes.length
}, 3000)
// 启动复合动画
animateSlide()
animateRotation()
}
build() {
Stack() {
Column()
.width('100%')
.height('100%')
.linearGradient({
angle: this.gradientAngle,
direction: GradientDirection.LeftTop,
colors: this.colorSchemes[this.currentColorIndex],
repeating: true
})
.backgroundImageSize(400)//设置背景图尺寸
.backgroundImagePosition({ x: `${this.bgPositionX}%`, y: '50%' })//设置背景图位置
.transition({ type: TransitionType.All })
.animation({ duration: 1000 })
Column() {
Text('动态渐变背景')
.fontSize(24)
.fontColor(Color.Black)
}
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
.onClick(() => {
// 点击切换颜色方案
this.currentColorIndex = (this.currentColorIndex + 1) % this.colorSchemes.length
})
}
}
