DEV Community

Cover image for Image Caching, chainMode, Custom Dialog, State Manager, Relative Position Setting
kouwei qing
kouwei qing

Posted on

Image Caching, chainMode, Custom Dialog, State Manager, Relative Position Setting

[Daily HarmonyOS Next Knowledge] Image Caching, chainMode, Custom Dialog, State Manager, Relative Position Setting

1. Can the image component in HarmonyOS cache network images?

When loading network images, the Image component reads resources from the network for the first time, and subsequent loads are read from the cache. For specific image caching details, refer to the documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-system-app-V5

static setImageCacheCount(value: number): void

Sets the upper limit of decoded images cached in memory to improve loading speed for the same source. The default is 0 (no caching). The cache uses a built-in LRU strategy: if the limit is exceeded, the least recently used cache is removed. Set a reasonable value based on memory requirements to avoid high memory usage.

  • This method takes effect when set in onPageShow or aboutToAppear of an @Entry-marked page.
  • setImageCacheCount, setImageRawDataCacheSize, and setImageFileCacheSize have limited flexibility. For complex scenarios, use ImageKnife instead.
// xxx.ets
import app, { AppResponse } from '@system.app'

@Entry
@Component
struct Index {
  onPageShow() {
    // Set the memory cache limit for decoded images to 100
    app.setImageCacheCount(100) 
    console.info('Application onPageShow')
  }
  onDestroy() {
    console.info('Application onDestroy')
  }

  build() {
    Row(){
      // xxxxxxxxxxxxx is the image URL
      Image('xxxxxxxxxxxxx')
        .width(200)
        .height(50)
    }.width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

static setImageRawDataCacheSize(value: number): void

Sets the upper limit (in bytes) for raw image data cached in memory before decoding. The default is 0 (no caching). The LRU strategy applies: if the limit is exceeded, the least recently used raw data is removed. Adjust the value to balance memory usage.

// xxx.ets
import app, { AppResponse } from '@system.app'

@Entry
@Component
struct Index {
  onPageShow() {
    // Set the memory cache limit for raw image data to 100MB (100MB = 100*1024*1024B = 104857600B)
    app.setImageRawDataCacheSize(104857600) 
    console.info('Application onPageShow')
  }
  onDestroy() {
    console.info('Application onDestroy')
  }

  build() {
    Row(){
      // xxxxxxxxxxxxx is the image URL
      Image('xxxxxxxxxxxxx')
        .width(200)
        .height(50)
    }.width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Why does chainMode not work in the vertical direction for HarmonyOS api RelativeContainer?

When using horizontal chainMode for three components (A, B, C), it works, but vertical chainMode for two components (A, B) fails.

For vertical chainMode, set the chain direction to Axis.Vertical and ensure the layout links to the parent container with connected anchors. Refer to dependency rules: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-relativecontainer-V5

@Entry
@Component
struct Index {
  build() {
    Row() {
      RelativeContainer() {
        Stack(){
          Image("Any image").width(80).aspectRatio(1).objectFit(ImageFit.Cover)
            .alt($r('app.media.background'))
        }.borderRadius('11vp').clip(true)
        .id('image')
        .alignRules({
          top: {anchor: "__container__", align: VerticalAlign.Top},
          bottom:{ anchor: 'a', align: VerticalAlign.Top},
          middle: {anchor: "__container__", align: HorizontalAlign.Center}
        })
        .id("row1")
        .chainMode(Axis.Vertical, ChainStyle.SPREAD)
        Row().width(80).height(80)
          .backgroundColor("#FFCC00")
          .alignRules({
            top: {anchor: "row1", align: VerticalAlign.Bottom},
            bottom: {anchor: "b", align: VerticalAlign.Top},
            left: {anchor: "row1", align: HorizontalAlign.Start}
          })
          .id("a")
        Row().width(80).height(80)
          .backgroundColor("#FF6633")
          .alignRules({
            top: {anchor: "a", align: VerticalAlign.Bottom},
            bottom: {anchor: "__container__", align : VerticalAlign.Bottom},
            left: {anchor: "row1", align: HorizontalAlign.Start}
          })
          .id("b")
      }
      .id('test')
      .width(300).height(300)
      .margin({left: 50})
      .border({width:2, color: "#6699FF"})
    }
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

3. When using @CustomDialog to decorate a pop-up, using @ObjectLink causes an error. Can it be decorated with @Component simultaneously?

Yes, @Component can decorate a @CustomDialog pop-up component, and decorators work normally. Here's a sample using @ObjectLink in a dialog:

@Observed
class Person {
  name: string = "Jerry"
  age: number = 0
}

@CustomDialog
@Component
struct CustomDialogExample {
  @ObjectLink curPerson: Person
  controller?: CustomDialogController
  build() {
    Column() {
      TextInput({text: this.curPerson.name})
        .onChange((input: string) => {
          this.curPerson.name = input
        })
        .width("100%")
        .height(100)
    }
    .width("100%")
    .backgroundColor(Color.White)
    .borderRadius({topLeft: 32, topRight: 32})
  }
}
@Entry
@Component
struct CustomDialogTest {
  @State person: Person = new Person()
  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogExample({curPerson: this.person}),
    alignment: DialogAlignment.Bottom,
    customStyle: true
  })
  build() {
    RelativeContainer() {
      Text(this.person.name)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: 'container', align: VerticalAlign.Center },
          middle: { anchor: 'container', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.dialogController.open()
        })
    }
    .height('100%')
    .width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Does HarmonyOS have a state manager similar to Flutter's provider?

Refer to the state management documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-state-management-overview-V5

In declarative UI frameworks, the UI is a function of the program's state. When state parameters change, the UI updates accordingly. This mechanism in ArkUI is called state management.

Custom components use variables decorated by decorators to become state variables. Changes to state variables trigger UI re-rendering. Without state variables, the UI only renders once during initialization.

5. How to set relative positions for child controls in a HarmonyOS Stack?

Setting align(Alignment.End) fails to place a close button on the far right. Use the following approach:

.alignRules({
  top: {anchor: "__container__", align: VerticalAlign.Top},
  left: {anchor: "__container__", align: HorizontalAlign.Start}
})
Enter fullscreen mode Exit fullscreen mode

For specific examples, refer to: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-relativecontainer-V5

Top comments (0)