目录

如何根据API版本动态增加Image组件的属性

问题现象

如何根据不同的API版本动态设置Image组件的属性?如:orientation属性在API 14及以上版本上生效,如何动态添加此属性?

背景知识

解决方案

可以通过获取deviceInfo.sdkApiVersion判断当前系统的API版本再使用动态属性设置需要的属性,如:

为Image组件设置attributeModifier动态属性:

import { deviceInfo } from '@kit.BasicServicesKit';


@Entry
@Component
struct Index {
  @State modifierImg: ImageModifier = new ImageModifier();


  aboutToAppear(): void {
    // 设置动态属性判断的API版本
    this.modifierImg.sdkApiVersionInfo = deviceInfo.sdkApiVersion;
  }


  build() {
    Flex({justifyContent: FlexAlign.Center}) {
      // 加载的图片请替换为实际项目所需图片资源
      Image($r('app.media.img'))
        .width(100)
        .height(100)
        .draggable(true)
        .attributeModifier(this.modifierImg)
    }
  }
}

通过判断API版本动态设置orientation属性:

export class ImageModifier implements AttributeModifier<ImageAttribute> {
  // 可以实现一个Modifier,定义私有的成员变量,外部可动态修改
  sdkApiVersionInfo: number = 12;
  applyNormalAttribute(instance: ImageAttribute): void {
    if (deviceInfo.sdkApiVersion >= 14) { // 支持业务逻辑实现
      // 属性变化触发apply函数时,变化前已设置并且变化后未设置的属性会恢复为默认值
      instance.orientation(ImageRotateOrientation.RIGHT);
    }
  }
}

示例代码运行效果如下:

系统API版本小于API 14:

系统API版本大于API 14: