按压Image组件时里面更换图片,手指松开复原 (HarmonyOS 鸿蒙Next)

按压Image组件时里面更换图片,手指松开复原 (HarmonyOS 鸿蒙Next) 按压Image组件时里面更换图片,手指松开复原

2 回复
@Entry
@Component
struct Progress_Ring {
  @State isPressed: boolean = true;
  build() {
    Row(){
      Image(this.isPressed? $r('app.media.startIcon') : $r('app.media.background'))
        .width(50).height(50)
    }
    .gesture(
      GestureGroup(GestureMode.Parallel,
        TapGesture()
          .onAction((event: GestureEvent|undefined) => {
            if(event){
              console.info('进入点击')
            }
          }),
        LongPressGesture({ repeat: true,duration:100 })
          .onAction((event: GestureEvent|undefined) => {
            this.isPressed = false;
          })
          .onActionEnd(() => {
            this.isPressed = true;
          })
      )
    )
  }
}

更多关于按压Image组件时里面更换图片,手指松开复原 (HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,可以通过Image组件和TouchEvent事件来实现按压时更换图片,手指松开时复原的效果。以下是一个示例代码片段:

import { Image, TouchEvent } from '@ohos.ultra';

@Entry
@Component
struct ImagePressExample {
  @State imageSrc: Resource = $r('app.media.normal_image'); // 默认图片

  build() {
    Column() {
      Image(this.imageSrc)
        .onTouch((event: TouchEvent) => {
          if (event.type === TouchType.Down) {
            this.imageSrc = $r('app.media.pressed_image'); // 按压时更换的图片
          } else if (event.type === TouchType.Up) {
            this.imageSrc = $r('app.media.normal_image'); // 手指松开时复原的图片
          }
        })
    }
  }
}

在这个示例中,Image组件通过onTouch方法监听触摸事件。当检测到TouchType.Down时,imageSrc状态变量被更新为按压时的图片资源;当检测到TouchType.Up时,imageSrc状态变量被更新为默认的图片资源,从而实现按压时更换图片,手指松开时复原的效果。

回到顶部