HarmonyOS 鸿蒙Next arkTs如何实现image的透明度从0到1的渐变动画,次数为无限次数
HarmonyOS 鸿蒙Next arkTs如何实现image的透明度从0到1的渐变动画,次数为无限次数 想实现一个image图片的动画效果,从透明度1渐变到0,次数为无数次,如何实现
用了如下设置后,动画播放了几次就停了,如何解决呢
let _this = this
let options : AnimatorOptions = {
duration: 1000,
easing: "ease",
delay: 0,
fill: "none",
direction: "normal",
iterations: -1,
begin: 0,
end: 1
}
let result = animator.create(options)
result.onframe = function(e){
_this.alpha = e
}
result.play()
Image($r('app.media.warn_red'))
.width(300)
.opacity(this.alpha)
更多关于HarmonyOS 鸿蒙Next arkTs如何实现image的透明度从0到1的渐变动画,次数为无限次数的实战教程也可以访问 https://www.itying.com/category-93-b0.html
6 回复
和你写的几乎一样,你试一试我这个行不行
```javascript
import animator, { AnimatorResult } from '[@ohos](/user/ohos).animator';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
private alphaAnimator: AnimatorResult = undefined
[@State](/user/State) alpha: number = 1;
create() {
let _this = this
this.alphaAnimator = animator.create({
duration: 1000,
easing: "ease",
delay: 0,
fill: "none",
direction: "normal",
iterations: -1,
begin: 0,
end: 1
})
this.alphaAnimator.onframe = function(value) {
_this.alpha = value
}
this.alphaAnimator.play()
}
aboutToDisappear() {
// 由于alphaAnimator在onframe中引用了this, this中保存了alphaAnimator,
// 在自定义组件消失时应该将保存在组件中的alphaAnimator置空,避免内存泄漏
this.alphaAnimator = undefined;
}
build() {
Column(){
Image($r('app.media.app_icon'))
.width(100)
.height(100)
.opacity(this.alpha)
.onAppear(() => {
this.create()
})
}
.alignItems(HorizontalAlign.Center)
.height('100%')
.width('100%')
}
}
更多关于HarmonyOS 鸿蒙Next arkTs如何实现image的透明度从0到1的渐变动画,次数为无限次数的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
代码片段
public void onBackPress() {
// 在这里添加处理逻辑
}
评论区代码
// 你的代码
处理过了呀,组件销毁的时候已经销毁了
aboutToDisappear() {
// 由于alphaAnimator在onframe中引用了this, this中保存了alphaAnimator,
// 在自定义组件消失时应该将保存在组件中的alphaAnimator置空,避免内存泄漏
this.alphaAnimator = undefined;
}
你在这个方法中加个log打印一下
console.info('tip',` 帧数${value} `)
然后你返回上一个页面,
在页面返回的时候, 把动画结束,要不会一直触发这个onframe方法
onBackPress(){
this.alphaAnimator.finish()
}
在HarmonyOS鸿蒙Next中,使用ArkTS实现Image的透明度从0到1的渐变动画,并且动画无限循环,可以通过animation
和@State
来实现。以下是一个简单的示例代码:
import { Image, animation, State } from '@ohos.arkui';
@Entry
@Component
struct ImageAnimationExample {
@State opacity: number = 0;
build() {
Image($r('app.media.example_image'))
.opacity(this.opacity)
.onAppear(() => {
animation({
duration: 1000, // 动画时长1秒
iterations: -1, // 无限循环
easing: 'ease-in-out'
}).keyframes([
{ percent: 0, opacity: 0 },
{ percent: 100, opacity: 1 }
]).onframe((value) => {
this.opacity = value.opacity;
}).play();
});
}
}
在这个示例中,@State
修饰的opacity
用于控制Image的透明度。animation
定义了动画的时长、循环次数和缓动效果。keyframes
指定了透明度的变化范围,onframe
回调函数根据动画进度更新opacity
的值,从而实现透明度从0到1的渐变动画。