HarmonyOS鸿蒙Next中用cangjie的Timer、slider、image写了一个转动图片的页面,运行后转了一会就不动了,有时会崩溃
HarmonyOS鸿蒙Next中用cangjie的Timer、slider、image写了一个转动图片的页面,运行后转了一会就不动了,有时会崩溃
Column() {
Image(@rawfile("windmill.png"))
.objectFit(ImageFit.Contain)
.width(Constants.IMAGE_SIZE)
.height(Constants.IMAGE_SIZE)
.rotate(
x: RotatePosition.X,
y: RotatePosition.Y,
z: RotatePosition.Z,
angle:this.angle,
)
.scale(x:this.imageSize, y:this.imageSize)
Slider(min:SliderSpeed.MIN, max:SliderSpeed.MAX, step:SliderSpeed.STEP, style: SliderStyle.InSet)
.layoutWeight(Constants.LAYOUT_WEIGHT)
.selectedColor(Constants.SLIDER_SKIN)
.onChange({value: Float64, mode: SliderChangeMode =>
// this.speed = Float32(value)
// this.timer.getOrThrow().cancel()
this.timer = Timer.repeat(Duration.millisecond*150, Duration.millisecond*150, { =>
this.angle += Float32(value) })
})
.margin( left: Constants.SLIDER_MARGIN_HORIZONTAL,
right: Constants.SLIDER_MARGIN_HORIZONTAL )
代码如上,刚开始图片会转一会,过段时间后就停止了,程序有时会崩溃,这是什么原因?
更多关于HarmonyOS鸿蒙Next中用cangjie的Timer、slider、image写了一个转动图片的页面,运行后转了一会就不动了,有时会崩溃的实战教程也可以访问 https://www.itying.com/category-93-b0.html
this.angle += Float32(value) })
// 切到UI线程试试
spwan(Main){
this.angle += Float32(value) })
}
https://developer.huawei.com/consumer/cn/doc/cangjie-references-V5/cj-appendix-thread-V5
更多关于HarmonyOS鸿蒙Next中用cangjie的Timer、slider、image写了一个转动图片的页面,运行后转了一会就不动了,有时会崩溃的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
问题可能由Timer未正确释放或Slider值异常触发。检查Timer的cancel()和stop()是否在onPageHide或onDestroy中调用,避免内存泄漏。Slider的onChange事件需防抖,防止频繁触发重绘导致UI卡顿或崩溃。Image的旋转角度计算需限制在0-360度范围内,避免数值溢出。使用@State管理旋转状态,确保UI同步。崩溃日志可定位具体异常类型。
代码中存在两个关键问题导致动画停止和崩溃:
- Timer未正确管理:每次Slider的onChange事件都会创建新的Timer实例,但未清理之前的Timer。这会导致多个Timer同时运行,造成资源竞争和内存泄漏。建议在创建新Timer前先取消现有Timer:
this.timer?.cancel()
this.timer = Timer.repeat(Duration.millisecond*150, Duration.millisecond*150, { => {
this.angle += Float32(value)
}})
- 角度值无限增长:angle属性持续累加而没有复位机制,当超过数值范围时可能导致渲染异常。建议添加角度复位逻辑:
this.angle = (this.angle + Float32(value)) % 360
同时检查SliderSpeed常量的取值是否合理,避免传入过大的旋转增量值。