| @@ -1136,6 +1136,8 @@ Downsampling strategy. | |||
| 1136 | | removeAllFileCache | cacheName?: string | Remove all file cache | | 1136 | | removeAllFileCache | cacheName?: string | Remove all file cache | |
| 1137 | | removeFileCache | url: string \| ImageKnifeOption \| ImageKnifeOptionV2 | Remove specified file cache | | 1137 | | removeFileCache | url: string \| ImageKnifeOption \| ImageKnifeOptionV2 | Remove specified file cache | |
| 1138 | | putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?: string | Write to memory/disk cache | | 1138 | | putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?: string | Write to memory/disk cache | |
| 1139 | +| clearOnBackground | - | Clears all memory caches, retains image memory for ImageKnife components within the visible area of the current page, and releases image memory held by all other ImageKnife components to reduce memory usage after the app moves to the background.<br>Can be called in the `onBackground` callback of `EntryAbility`.<br>Should be used together with `reloadOnForeground`. | | ||
| 1140 | +| reloadOnForeground | - | Reloads images for components whose image data was cleared when the app returns to the foreground.<br>Can be called in the `onForeground` callback of `EntryAbility`.<br>Should be used together with `clearOnBackground`. | | ||
| 1139 | 1141 | ||
| 1140 | ### Callbacks | 1142 | ### Callbacks |
| 1141 | 1143 | ||
| @@ -1178,6 +1178,8 @@ HTTP 请求参数。 | |||
| 1178 | | removeAllFileCache | cacheName?: string | 清理所有文件缓存 | | 1178 | | removeAllFileCache | cacheName?: string | 清理所有文件缓存 | |
| 1179 | | removeFileCache | url: string \| ImageKnifeOption \| ImageKnifeOptionV2 | 清除指定文件缓存 | | 1179 | | removeFileCache | url: string \| ImageKnifeOption \| ImageKnifeOptionV2 | 清除指定文件缓存 | |
| 1180 | | putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?: string | 写入内存/磁盘缓存 | | 1180 | | putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?: string | 写入内存/磁盘缓存 | |
| 1181 | +| clearOnBackground | - | 清除所有内存缓存,保留当前页面在屏幕范围内的组件图片内存,清除其余所有ImageKnife组件所持有的图片内存,以减少应用退后台后的内存占用<br> 可以在EntryAbility的onBackground回调中调用<br> 需要配和reloadOnForeground使用| | ||
| 1182 | +| reloadOnForeground | - | 在应用切换至前台时重新加载被清空的组件图片<br> 可以在EntryAbility的onForeground回调中调用<br> 需要配和clearOnBackground使用| | ||
| 1181 | 1183 | ||
| 1182 | ### 回调接口说明 | 1184 | ### 回调接口说明 |
| 1183 | 1185 | ||
| @@ -96,11 +96,13 @@ export default class EntryAbility extends UIAbility { | |||
| 96 | 96 | ||
| 97 | onForeground(): void { | 97 | onForeground(): void { |
| 98 | // Ability has brought to foreground | 98 | // Ability has brought to foreground |
| 99 | + ImageKnife.getInstance().reloadOnForeground(); | ||
| 99 | hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); | 100 | hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); |
| 100 | } | 101 | } |
| 101 | 102 | ||
| 102 | onBackground(): void { | 103 | onBackground(): void { |
| 103 | // Ability has back to background | 104 | // Ability has back to background |
| 105 | + ImageKnife.getInstance().clearOnBackground(); | ||
| 104 | hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); | 106 | hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); |
| 105 | } | 107 | } |
| 106 | }; | 108 | }; |
| @@ -66,6 +66,11 @@ struct Index { | |||
| 66 | url: 'pages/PreCreateImageNode', | 66 | url: 'pages/PreCreateImageNode', |
| 67 | }) | 67 | }) |
| 68 | }) | 68 | }) |
| 69 | + Button('测试应用退后台清理图片内存').margin({top:10}).onClick(()=>{ | ||
| 70 | + router.pushUrl({ | ||
| 71 | + url: "pages/onbackground/TestAppOnBackground", | ||
| 72 | + }) | ||
| 73 | + }) | ||
| 69 | Button('Crc32校验').margin({top:10}).onClick(()=>{ | 74 | Button('Crc32校验').margin({top:10}).onClick(()=>{ |
| 70 | router.pushUrl({ | 75 | router.pushUrl({ |
| 71 | url: 'pages/CheckImageCrc32', | 76 | url: 'pages/CheckImageCrc32', |
| @@ -88,7 +88,7 @@ export struct LazyForEachTwo { | |||
| 88 | .backgroundColor('#95efd2') | 88 | .backgroundColor('#95efd2') |
| 89 | }, (item: string) => item) | 89 | }, (item: string) => item) |
| 90 | } | 90 | } |
| 91 | - .cachedCount(0) | 91 | + .cachedCount(4) |
| 92 | .columnsTemplate('1fr 1fr') | 92 | .columnsTemplate('1fr 1fr') |
| 93 | .columnsGap(10) | 93 | .columnsGap(10) |
| 94 | .rowsGap(5) | 94 | .rowsGap(5) |
| @@ -0,0 +1,69 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (C) 2026 Huawei Device Co., Ltd. | ||
| 3 | + * Licensed under the Apache License, Version 2.0 (the 'License'); | ||
| 4 | + * you may not use this file except in compliance with the License. | ||
| 5 | + * You may obtain a copy of the License at | ||
| 6 | + * | ||
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 | ||
| 8 | + * | ||
| 9 | + * Unless required by applicable law or agreed to in writing, software | ||
| 10 | + * distributed under the License is distributed on an 'AS IS' BASIS, | ||
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 12 | + * See the License for the specific language governing permissions and | ||
| 13 | + * limitations under the License. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +import { ImageKnifeOption, ImageKnifeView } from '@ohos/imageknifepro'; | ||
| 17 | +import { CommonDataSource } from '../model/CommonDataSource'; | ||
| 18 | +import { dataArray } from '../model/ImageUrlData'; | ||
| 19 | +import { router } from '@kit.ArkUI'; | ||
| 20 | + | ||
| 21 | +@Entry | ||
| 22 | +@ComponentV2 | ||
| 23 | +export struct TestPage { | ||
| 24 | + @Local hotCommendList:CommonDataSource<string> = new CommonDataSource<string>([]) | ||
| 25 | + aboutToAppear(): void { | ||
| 26 | + this.hotCommendList.addData(this.hotCommendList.totalCount(),dataArray) | ||
| 27 | + } | ||
| 28 | + build() { | ||
| 29 | + Column() { | ||
| 30 | + WaterFlow() { | ||
| 31 | + LazyForEach(this.hotCommendList,(item: string,index:number)=>{ | ||
| 32 | + FlowItem() { | ||
| 33 | + Column(){ | ||
| 34 | + ImageComponent({ | ||
| 35 | + imageKnifeOption: { | ||
| 36 | + loadSrc: item, | ||
| 37 | + placeholderSrc: $r("app.media.loading"), | ||
| 38 | + errorSrc: $r("app.media.failed"), | ||
| 39 | + } | ||
| 40 | + }).width("50%").height(160) | ||
| 41 | + Text(index + "") | ||
| 42 | + } | ||
| 43 | + }.height(200) | ||
| 44 | + .backgroundColor("#95efd2") | ||
| 45 | + },(item: string) => item) | ||
| 46 | + }.columnsTemplate("1fr 1fr") | ||
| 47 | + .columnsGap(10) | ||
| 48 | + .rowsGap(5) | ||
| 49 | + .backgroundColor(0xFAEEE0) | ||
| 50 | + .width("100%").height("90%") | ||
| 51 | + | ||
| 52 | + Button("进入新的页面").onClick(()=> { | ||
| 53 | + router.pushUrl({ | ||
| 54 | + url: "pages/onbackground/TestOnBackgroundPage", | ||
| 55 | + }) | ||
| 56 | + }).margin({top:10}) | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +@Component | ||
| 62 | +struct ImageComponent { | ||
| 63 | + @State imageKnifeOption: ImageKnifeOption = new ImageKnifeOption() | ||
| 64 | + build() { | ||
| 65 | + ImageKnifeView({ | ||
| 66 | + imageKnifeOption: this.imageKnifeOption | ||
| 67 | + }) | ||
| 68 | + } | ||
| 69 | +} | ||
| @@ -0,0 +1,36 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (C) 2026 Huawei Device Co., Ltd. | ||
| 3 | + * Licensed under the Apache License, Version 2.0 (the 'License'); | ||
| 4 | + * you may not use this file except in compliance with the License. | ||
| 5 | + * You may obtain a copy of the License at | ||
| 6 | + * | ||
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 | ||
| 8 | + * | ||
| 9 | + * Unless required by applicable law or agreed to in writing, software | ||
| 10 | + * distributed under the License is distributed on an 'AS IS' BASIS, | ||
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 12 | + * See the License for the specific language governing permissions and | ||
| 13 | + * limitations under the License. | ||
| 14 | + */ | ||
| 15 | +import { ImageKnifeConstWrapper } from '../component/ComponentWrapper'; | ||
| 16 | + | ||
| 17 | +@Entry | ||
| 18 | +@Component | ||
| 19 | +struct TestOnBackGroundDetailPage { | ||
| 20 | + @State message: string = '详情页'; | ||
| 21 | + | ||
| 22 | + build() { | ||
| 23 | + Column() { | ||
| 24 | + Text(this.message).margin(30).fontSize(20) | ||
| 25 | + | ||
| 26 | + ImageKnifeConstWrapper({ | ||
| 27 | + imageKnifeOption: { | ||
| 28 | + loadSrc:$r("app.media.pngSample") | ||
| 29 | + } | ||
| 30 | + }).width(300).height(500) | ||
| 31 | + | ||
| 32 | + } | ||
| 33 | + .height('100%') | ||
| 34 | + .width('100%') | ||
| 35 | + } | ||
| 36 | +} | ||
| @@ -0,0 +1,143 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (C) 2026 Huawei Device Co., Ltd. | ||
| 3 | + * Licensed under the Apache License, Version 2.0 (the 'License'); | ||
| 4 | + * you may not use this file except in compliance with the License. | ||
| 5 | + * You may obtain a copy of the License at | ||
| 6 | + * | ||
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 | ||
| 8 | + * | ||
| 9 | + * Unless required by applicable law or agreed to in writing, software | ||
| 10 | + * distributed under the License is distributed on an 'AS IS' BASIS, | ||
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 12 | + * See the License for the specific language governing permissions and | ||
| 13 | + * limitations under the License. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +import { CommonDataSource } from "../model/CommonDataSource" | ||
| 17 | +import { mapData, mapDataKeys } from "../model/ImageUrlData" | ||
| 18 | +import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro' | ||
| 19 | +import deviceInfo from '@ohos.deviceInfo' | ||
| 20 | +import { router } from "@kit.ArkUI" | ||
| 21 | +import { image } from "@kit.ImageKit" | ||
| 22 | + | ||
| 23 | +@Entry | ||
| 24 | +@Component | ||
| 25 | +export struct TestPage { | ||
| 26 | + private columnCounts = "1fr 1fr"; | ||
| 27 | + @State hotCommendList:CommonDataSource<string> = new CommonDataSource<string>([]) | ||
| 28 | + | ||
| 29 | + private pixelMap?: PixelMap; | ||
| 30 | + @State private optionPixelMap:ImageKnifeOption = { | ||
| 31 | + loadSrc:"" | ||
| 32 | + } | ||
| 33 | + aboutToAppear(): void { | ||
| 34 | + let icon: Uint8Array = getContext(this).resourceManager.getMediaContentSync($r('app.media.startIcon')); | ||
| 35 | + | ||
| 36 | + let imageSource: image.ImageSource = image.createImageSource(icon.buffer); | ||
| 37 | + if (imageSource) { | ||
| 38 | + let decodingOptions: image.DecodingOptions = { | ||
| 39 | + editable: true, | ||
| 40 | + } | ||
| 41 | + this.pixelMap = imageSource.createPixelMapSync(decodingOptions); | ||
| 42 | + this.optionPixelMap.loadSrc = this.pixelMap! | ||
| 43 | + imageSource.release(); | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + if (deviceInfo.deviceType == "tablet") { | ||
| 47 | + this.columnCounts = "1fr 1fr 1fr"; | ||
| 48 | + } | ||
| 49 | + this.hotCommendList.addData(this.hotCommendList.totalCount(), mapDataKeys) | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + aboutToDisappear(): void { | ||
| 53 | + this.pixelMap?.release() | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + build() { | ||
| 57 | + Column() { | ||
| 58 | + ImageKnifeComponent({ | ||
| 59 | + imageKnifeOption:this.optionPixelMap | ||
| 60 | + }).width(100).height(100).margin(10) | ||
| 61 | + | ||
| 62 | + WaterFlow() { | ||
| 63 | + LazyForEach(this.hotCommendList, (key: string)=>{ | ||
| 64 | + FlowItem() { | ||
| 65 | + AppListItem({ | ||
| 66 | + url:mapData[key], | ||
| 67 | + appName:key | ||
| 68 | + }) | ||
| 69 | + } | ||
| 70 | + }, (key: string) => key) | ||
| 71 | + }.columnsTemplate(this.columnCounts) | ||
| 72 | + .width("100%").height("80%") | ||
| 73 | + | ||
| 74 | + Button("进入详情页").onClick(()=> { | ||
| 75 | + router.pushUrl({ | ||
| 76 | + url: "pages/onbackground/TestOnBackGroundDetailPage", | ||
| 77 | + }) | ||
| 78 | + }).margin({top:10}) | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +@Reusable | ||
| 84 | +@Component | ||
| 85 | +struct AppListItem { | ||
| 86 | + @State appName: string = "" | ||
| 87 | + url: string = "" | ||
| 88 | + @State description: string = "" | ||
| 89 | + @State imageKnifeOption:ImageKnifeOption = { | ||
| 90 | + loadSrc: this.url, | ||
| 91 | + placeholderSrc: $r("app.media.loading"), | ||
| 92 | + errorSrc: $r("app.media.failed"), | ||
| 93 | + border:{radius:10}, | ||
| 94 | + onLoadListener: { | ||
| 95 | + onLoadStart: (imageInfo) => { | ||
| 96 | + this.description = "应用描述:" + imageInfo.requestId; | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + }; | ||
| 100 | + | ||
| 101 | + aboutToAppear(): void { | ||
| 102 | + this.imageKnifeOption.loadSrc = this.url; | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + aboutToReuse(params: ESObject): void { | ||
| 106 | + this.imageKnifeOption.loadSrc = params.url | ||
| 107 | + this.appName = params.appName | ||
| 108 | + if (this.imageKnifeOption.forceWatch != undefined) { | ||
| 109 | + this.imageKnifeOption.forceWatch++; | ||
| 110 | + } else { | ||
| 111 | + this.imageKnifeOption.forceWatch = 0; | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + build() { | ||
| 116 | + Row() { | ||
| 117 | + ImageKnifeComponent({ | ||
| 118 | + imageKnifeOption:this.imageKnifeOption | ||
| 119 | + }).width(48).height(48) | ||
| 120 | + .margin({left:12, right:12}) | ||
| 121 | + | ||
| 122 | + Column() { | ||
| 123 | + Text(this.appName) | ||
| 124 | + .fontSize(16) | ||
| 125 | + .fontWeight(FontWeight.Medium) | ||
| 126 | + .textOverflow({overflow:TextOverflow.Ellipsis}) | ||
| 127 | + .layoutWeight(1) | ||
| 128 | + | ||
| 129 | + Text(this.description) | ||
| 130 | + .fontSize(12) | ||
| 131 | + .fontColor(Color.Gray) | ||
| 132 | + .textOverflow({overflow:TextOverflow.Ellipsis}) | ||
| 133 | + } | ||
| 134 | + .height(48) | ||
| 135 | + .flexGrow(1) | ||
| 136 | + .alignItems(HorizontalAlign.Start) | ||
| 137 | + .margin({right:10}) | ||
| 138 | + } | ||
| 139 | + .width('100%') | ||
| 140 | + .height(60) | ||
| 141 | + .alignItems(VerticalAlign.Center) | ||
| 142 | + } | ||
| 143 | +} | ||
| @@ -106,6 +106,9 @@ | |||
| 106 | "pages/TestOnLoadCallback", | 106 | "pages/TestOnLoadCallback", |
| 107 | "pages/TestOnLoadEndRequestMerged", | 107 | "pages/TestOnLoadEndRequestMerged", |
| 108 | "pages/TestGlobalLoadEndCallback", | 108 | "pages/TestGlobalLoadEndCallback", |
| 109 | - "pages/ShowAllImageType" | 109 | + "pages/ShowAllImageType", |
| 110 | + "pages/onbackground/TestAppOnBackground", | ||
| 111 | + "pages/onbackground/TestOnBackgroundPage", | ||
| 112 | + "pages/onbackground/TestOnBackGroundDetailPage" | ||
| 110 | ] | 113 | ] |
| 111 | } | 114 | } |
| @@ -56,4 +56,50 @@ ArkuiApi::UnregisterCommonEvent ArkuiApi::GetApiUnregisterCommonEvent() | |||
| 56 | return api; | 56 | return api; |
| 57 | } | 57 | } |
| 58 | 58 | ||
| 59 | +ArkuiApi::GetCurrentPageRootNode ArkuiApi::GetApiGetCurrentPageRootNode() | ||
| 60 | +{ | ||
| 61 | + constexpr int apiMinVersion = 14; | ||
| 62 | + const char *funcName = "OH_ArkUI_NodeUtils_GetCurrentPageRootNode"; | ||
| 63 | + static auto api = GetApiTemplate<GetCurrentPageRootNode, apiMinVersion>(funcName); | ||
| 64 | + return api; | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +ArkuiApi::GetChildIndexWithoutExpand ArkuiApi::GetApiGetFirstChildIndexWithoutExpand() | ||
| 68 | +{ | ||
| 69 | + constexpr int apiMinVersion = 15; | ||
| 70 | + const char *funcName = "OH_ArkUI_NodeUtils_GetFirstChildIndexWithoutExpand"; | ||
| 71 | + static auto api = GetApiTemplate<GetChildIndexWithoutExpand, apiMinVersion>(funcName); | ||
| 72 | + return api; | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +ArkuiApi::GetChildIndexWithoutExpand ArkuiApi::GetApiGetLastChildIndexWithoutExpand() | ||
| 76 | +{ | ||
| 77 | + constexpr int apiMinVersion = 15; | ||
| 78 | + const char *funcName = "OH_ArkUI_NodeUtils_GetLastChildIndexWithoutExpand"; | ||
| 79 | + static auto api = GetApiTemplate<GetChildIndexWithoutExpand, apiMinVersion>(funcName); | ||
| 80 | + return api; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +ArkuiApi::GetChildWithExpandMode ArkuiApi::GetApiGetChildWithExpandMode() | ||
| 84 | +{ | ||
| 85 | + constexpr int apiMinVersion = 15; | ||
| 86 | + const char *funcName = "OH_ArkUI_NodeUtils_GetChildWithExpandMode"; | ||
| 87 | + static auto api = GetApiTemplate<GetChildWithExpandMode, apiMinVersion>(funcName); | ||
| 88 | + return api; | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +ArkuiApi::GetNodeType ArkuiApi::GetApiGetNodeType() | ||
| 92 | +{ | ||
| 93 | + constexpr int apiMinVersion = 14; | ||
| 94 | + static auto api = GetApiTemplate<GetNodeType, apiMinVersion>("OH_ArkUI_NodeUtils_GetNodeType"); | ||
| 95 | + return api; | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +ArkuiApi::GetNodeUniqueId ArkuiApi::GetApiGetNodeUniqueId() | ||
| 99 | +{ | ||
| 100 | + constexpr int apiMinVersion = 20; | ||
| 101 | + static auto api = GetApiTemplate<GetNodeUniqueId, apiMinVersion>("OH_ArkUI_NodeUtils_GetNodeUniqueId"); | ||
| 102 | + return api; | ||
| 103 | +} | ||
| 104 | + | ||
| 59 | } | 105 | } |
| @@ -30,11 +30,24 @@ public: | |||
| 30 | typedef int32_t (*RegisterCommonEvent) (ArkUI_NodeHandle node, ArkUI_NodeEventType eventType, | 30 | typedef int32_t (*RegisterCommonEvent) (ArkUI_NodeHandle node, ArkUI_NodeEventType eventType, |
| 31 | void* userData, void (*callback)(ArkUI_NodeEvent* event)); | 31 | void* userData, void (*callback)(ArkUI_NodeEvent* event)); |
| 32 | typedef int32_t (*UnregisterCommonEvent) (ArkUI_NodeHandle node, ArkUI_NodeEventType eventType); | 32 | typedef int32_t (*UnregisterCommonEvent) (ArkUI_NodeHandle node, ArkUI_NodeEventType eventType); |
| 33 | + typedef ArkUI_NodeHandle (*GetCurrentPageRootNode) (ArkUI_NodeHandle node); | ||
| 34 | + typedef int32_t (*GetChildIndexWithoutExpand) (ArkUI_NodeHandle node, uint32_t* index); | ||
| 35 | + typedef int32_t (*GetChildWithExpandMode) (ArkUI_NodeHandle node, int32_t position, | ||
| 36 | + ArkUI_NodeHandle* subnode, uint32_t expandMode); | ||
| 37 | + typedef int32_t (*GetNodeType) (ArkUI_NodeHandle node); | ||
| 38 | + typedef int32_t (*GetNodeUniqueId) (ArkUI_NodeHandle node, int32_t* uniqueId); | ||
| 33 | 39 | ||
| 34 | InvalidateAttributes GetApiInvalidateAttributes(); | 40 | InvalidateAttributes GetApiInvalidateAttributes(); |
| 35 | CreateContentTransitionEffect GetApiCreateContentTransitionEffect(); | 41 | CreateContentTransitionEffect GetApiCreateContentTransitionEffect(); |
| 36 | RegisterCommonEvent GetApiRegisterCommonEvent(); | 42 | RegisterCommonEvent GetApiRegisterCommonEvent(); |
| 37 | UnregisterCommonEvent GetApiUnregisterCommonEvent(); | 43 | UnregisterCommonEvent GetApiUnregisterCommonEvent(); |
| 44 | + | ||
| 45 | + GetCurrentPageRootNode GetApiGetCurrentPageRootNode(); | ||
| 46 | + GetChildIndexWithoutExpand GetApiGetFirstChildIndexWithoutExpand(); | ||
| 47 | + GetChildIndexWithoutExpand GetApiGetLastChildIndexWithoutExpand(); | ||
| 48 | + GetChildWithExpandMode GetApiGetChildWithExpandMode(); | ||
| 49 | + GetNodeType GetApiGetNodeType(); | ||
| 50 | + GetNodeUniqueId GetApiGetNodeUniqueId(); | ||
| 38 | }; | 51 | }; |
| 39 | } | 52 | } |
| 40 | 53 | ||
| @@ -64,8 +64,8 @@ bool OptionData::MovePixelMap(OH_PixelmapNative *&result) | |||
| 64 | { | 64 | { |
| 65 | if ((DataType::PIXELMAP & availableType_) && (type_ == DataType::PIXELMAP) && (data_.pixelMap != nullptr)) { | 65 | if ((DataType::PIXELMAP & availableType_) && (type_ == DataType::PIXELMAP) && (data_.pixelMap != nullptr)) { |
| 66 | result = data_.pixelMap; | 66 | result = data_.pixelMap; |
| 67 | + // pixelmap置空后已无法再次获取资源,保持原本data类型不变,能够追溯来源资源类型 | ||
| 67 | data_.pixelMap = nullptr; | 68 | data_.pixelMap = nullptr; |
| 68 | - type_ = DataType::UNDEFINED; | ||
| 69 | return true; | 69 | return true; |
| 70 | } | 70 | } |
| 71 | return false; | 71 | return false; |
| @@ -14,6 +14,8 @@ | |||
| 14 | */ | 14 | */ |
| 15 | 15 | ||
| 16 | #include <future> | 16 | #include <future> |
| 17 | +#include <window_manager/oh_display_manager.h> | ||
| 18 | +#include "api/imageknife_api.h" | ||
| 17 | #include "common.h" | 19 | #include "common.h" |
| 18 | #include "imageknife_dispatcher.h" | 20 | #include "imageknife_dispatcher.h" |
| 19 | #include "imageknife_internal.h" | 21 | #include "imageknife_internal.h" |
| @@ -839,4 +841,175 @@ bool ImageKnifeInternal::GetJpegOptimizeDecoding() const | |||
| 839 | return enableJpegOptimiseDecoding_; | 841 | return enableJpegOptimiseDecoding_; |
| 840 | } | 842 | } |
| 841 | 843 | ||
| 844 | +void ImageKnifeInternal::TraversalChildrenAsExpandMode(ArkUI_NodeHandle node, const int32_t &nodeId) | ||
| 845 | +{ | ||
| 846 | + static auto getNodeType = ImageKnifeApi::GetInstance().GetArkuiApi().GetApiGetNodeType(); | ||
| 847 | + if (getNodeType == nullptr) { | ||
| 848 | + return; | ||
| 849 | + } | ||
| 850 | + | ||
| 851 | + ArkUI_NodeHandle child = ArkUINode::GetNodeAPI()->getFirstChild(node); | ||
| 852 | + ArkUI_NodeHandle lastChild = ArkUINode::GetNodeAPI()->getLastChild(node); | ||
| 853 | + if (child == nullptr) { | ||
| 854 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d Not Found First Child", nodeId); | ||
| 855 | + return; | ||
| 856 | + } | ||
| 857 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d get child as expandMode", nodeId); | ||
| 858 | + constexpr int maxTime = 512; // 限制循环最大次数 | ||
| 859 | + int count = 0; | ||
| 860 | + while (child != nullptr && count < maxTime) { | ||
| 861 | + count++; | ||
| 862 | + TraversalNodeCheckChildInScreen(child, nodeId, getNodeType(child)); | ||
| 863 | + if (child == lastChild) { | ||
| 864 | + // 存在最后的节点获取下一个兄弟节点时,获取到自身的可能。为避免死循环,lastChild访问后主动跳出循环 | ||
| 865 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d Accessed Last Child as expandMode", nodeId); | ||
| 866 | + break; | ||
| 867 | + } | ||
| 868 | + child = ArkUINode::GetNodeAPI()->getNextSibling(child); | ||
| 869 | + } | ||
| 870 | +} | ||
| 871 | + | ||
| 872 | +void ImageKnifeInternal::TraversalNodeCheckChildInScreen(ArkUI_NodeHandle child, const int32_t &parentId, | ||
| 873 | + const int32_t &nodeType) | ||
| 874 | +{ | ||
| 875 | + ArkUI_IntOffset offset; | ||
| 876 | + OH_ArkUI_NodeUtils_GetLayoutPositionInScreen(child, &offset); | ||
| 877 | + ArkUI_IntSize measureSize = ArkUINode::GetNodeAPI()->getMeasuredSize(child); | ||
| 878 | + // 判断组件是否在屏幕范围内 | ||
| 879 | + if (measureSize.width > 0 && measureSize.height > 0 && | ||
| 880 | + offset.x < screenWidth_ && offset.y < screenHeight_ && | ||
| 881 | + offset.x + measureSize.width > 0 && offset.y + measureSize.height > 0) { | ||
| 882 | + // 判断是否为图片组件 | ||
| 883 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "TraversalNode:%{public}d, parent:%{public}d offset x:%{public}d, y:%{public}d, " | ||
| 884 | + "measure width:%{public}d, height:%{public}d, NodeType:%{public}d", | ||
| 885 | + GetNodeUniqueId(child), parentId, offset.x, offset.y, | ||
| 886 | + measureSize.width, measureSize.height, nodeType); | ||
| 887 | + if (nodeType == ARKUI_NODE_IMAGE || nodeType == ARKUI_NODE_CUSTOM) { | ||
| 888 | + // 记录在屏幕中的图片组件 | ||
| 889 | + currentScreenHandles_.insert(child); | ||
| 890 | + } else { | ||
| 891 | + // 非图片组件,遍历下一层子节点 | ||
| 892 | + TraversalNode(child, nodeType); | ||
| 893 | + } | ||
| 894 | + } else { | ||
| 895 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "TraversalNode:%{public}d, parent:%{public}d offset x:%{public}d, y:%{public}d," | ||
| 896 | + "measure width:%{public}d, height:%{public}d Not Exist In Screen", | ||
| 897 | + GetNodeUniqueId(child), parentId, offset.x, offset.y, | ||
| 898 | + measureSize.width, measureSize.height); | ||
| 899 | + } | ||
| 900 | +} | ||
| 901 | + | ||
| 902 | +void ImageKnifeInternal::TraversalNode(ArkUI_NodeHandle node, const int32_t &nodeType) | ||
| 903 | +{ | ||
| 904 | + if (node == nullptr) { | ||
| 905 | + return; | ||
| 906 | + } | ||
| 907 | + | ||
| 908 | + auto &arkuiAPi = ImageKnifeApi::GetInstance().GetArkuiApi(); | ||
| 909 | + static auto getFirstChildIndexWithoutExpand = arkuiAPi.GetApiGetFirstChildIndexWithoutExpand(); | ||
| 910 | + static auto getLastChildIndexWithoutExpand = arkuiAPi.GetApiGetLastChildIndexWithoutExpand(); | ||
| 911 | + static auto getChildWithExpandMode = arkuiAPi.GetApiGetChildWithExpandMode(); | ||
| 912 | + static auto getNodeType = arkuiAPi.GetApiGetNodeType(); | ||
| 913 | + if (getFirstChildIndexWithoutExpand == nullptr || getLastChildIndexWithoutExpand == nullptr || | ||
| 914 | + getChildWithExpandMode == nullptr || getNodeType == nullptr) { | ||
| 915 | + return; | ||
| 916 | + } | ||
| 917 | + | ||
| 918 | + int32_t nodeId = GetNodeUniqueId(node); | ||
| 919 | + if (nodeType == ARKUI_NODE_LIST || nodeType == ARKUI_NODE_LIST_ITEM_GROUP || nodeType == ARKUI_NODE_GRID || | ||
| 920 | + nodeType == ARKUI_NODE_SWIPER || nodeType == ARKUI_NODE_WATER_FLOW) { | ||
| 921 | + // 使用ARKUI_LAZY_EXPAND的展开方式遍历子节点,普通遍历方式会增加懒加载瀑布流中的节点数量 | ||
| 922 | + uint32_t firstIndex = 0; | ||
| 923 | + uint32_t lastIndex = 0; | ||
| 924 | + if (getFirstChildIndexWithoutExpand(node, &firstIndex) != ARKUI_ERROR_CODE_NO_ERROR || | ||
| 925 | + getLastChildIndexWithoutExpand(node, &lastIndex) != ARKUI_ERROR_CODE_NO_ERROR) { | ||
| 926 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d Not Found Child", nodeId); | ||
| 927 | + return; | ||
| 928 | + } | ||
| 929 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d first:%{public}d, last:%{public}d", nodeId, firstIndex, lastIndex); | ||
| 930 | + | ||
| 931 | + constexpr int maxTime = 512; // 限制循环最大次数 | ||
| 932 | + int count = 0; | ||
| 933 | + for (uint32_t index = firstIndex; index <= lastIndex && count < maxTime; index++) { | ||
| 934 | + count++; | ||
| 935 | + ArkUI_NodeHandle child = nullptr; | ||
| 936 | + int32_t errorCode = getChildWithExpandMode(node, index, &child, ARKUI_LAZY_EXPAND); | ||
| 937 | + if (child == nullptr || errorCode != ARKUI_ERROR_CODE_NO_ERROR) { | ||
| 938 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "Node:%{public}d expand child failed at index:%{public}d", nodeId, index); | ||
| 939 | + continue; | ||
| 940 | + } | ||
| 941 | + TraversalNodeCheckChildInScreen(child, nodeId, getNodeType(child)); | ||
| 942 | + } | ||
| 943 | + } else { | ||
| 944 | + // 普通的遍历方式,避免部分节点无法获取子节点的问题 | ||
| 945 | + TraversalChildrenAsExpandMode(node, nodeId); | ||
| 946 | + } | ||
| 947 | +} | ||
| 948 | + | ||
| 949 | +void ImageKnifeInternal::ClearOnBackground() | ||
| 950 | +{ | ||
| 951 | + ImageKnifeTrace trace("Clear OnBackground"); | ||
| 952 | + trace.StartSyncTrace(); | ||
| 953 | + ArkUI_NodeHandle rootNode = nullptr; | ||
| 954 | + // 考虑到折叠屏,屏幕宽高并非不变,屏幕宽高每次退后台获取一次 | ||
| 955 | + OH_NativeDisplayManager_GetDefaultDisplayWidth(&screenWidth_); | ||
| 956 | + OH_NativeDisplayManager_GetDefaultDisplayHeight(&screenHeight_); | ||
| 957 | + | ||
| 958 | + onForeGroundReloadNodeIds_.clear(); | ||
| 959 | + currentScreenHandles_.clear(); | ||
| 960 | + RemoveAllMemoryCache(); | ||
| 961 | + | ||
| 962 | + static auto getCurrentPageRootNode = ImageKnifeApi::GetInstance().GetArkuiApi().GetApiGetCurrentPageRootNode(); | ||
| 963 | + static auto getNodeType = ImageKnifeApi::GetInstance().GetArkuiApi().GetApiGetNodeType(); | ||
| 964 | + for (auto &[nodeId, node] : imageNodeMap_) { | ||
| 965 | + ArkUI_NodeHandle handle = node->GetHandle(); | ||
| 966 | + // 先检查组件是否在当前的路由页面 | ||
| 967 | + ArkUI_RouterPageState state; | ||
| 968 | + auto errorCode = OH_ArkUI_GetRouterPageState(handle, &state); | ||
| 969 | + if (errorCode == ARKUI_ERROR_CODE_NO_ERROR && state == ARKUI_ROUTER_PAGE_STATE_ON_SHOW) { | ||
| 970 | + // 低API版本不进行UI树遍历,仅清理隐藏页面的组件图片内存 | ||
| 971 | + constexpr int apiMinVersion = 15; | ||
| 972 | + if (ApiBase::GetApiVersion() < apiMinVersion) { | ||
| 973 | + continue; | ||
| 974 | + } | ||
| 975 | + // 获取当前页面根节点,遍历UI树,找到在屏幕范围内的组件 | ||
| 976 | + if (rootNode == nullptr && getCurrentPageRootNode != nullptr) { | ||
| 977 | + ImageKnifeTrace traceTraversal("Traversal RootNode"); | ||
| 978 | + traceTraversal.StartSyncTrace(); | ||
| 979 | + rootNode = getCurrentPageRootNode(handle); | ||
| 980 | + TraversalNode(rootNode, rootNode == nullptr ? -1 : getNodeType(rootNode)); | ||
| 981 | + traceTraversal.FinishTrace(); | ||
| 982 | + } | ||
| 983 | + | ||
| 984 | + // 检查该组件是否在屏幕上 | ||
| 985 | + if (currentScreenHandles_.find(handle) != currentScreenHandles_.end()) { | ||
| 986 | + // 存活组件,写回内存缓存 | ||
| 987 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "On Background Survival Node ID:%{public}d", GetNodeUniqueId(handle)); | ||
| 988 | + node->ResumeDataCache(); | ||
| 989 | + } else if (node->ClearOnBackground()) { | ||
| 990 | + // 此处被清理的进行记录,优先恢复 | ||
| 991 | + onForeGroundReloadNodeIds_.push_front(nodeId); | ||
| 992 | + } | ||
| 993 | + } else if (node->ClearOnBackground()) { | ||
| 994 | + // 非当前页面被清理,列表尾插 | ||
| 995 | + onForeGroundReloadNodeIds_.push_back(nodeId); | ||
| 996 | + } | ||
| 997 | + } | ||
| 998 | + | ||
| 999 | + IMAGE_KNIFE_LOG(LOG_INFO, "On Background Total Node:%{public}zu, Clear Node:%{public}zu", | ||
| 1000 | + imageNodeMap_.size(), onForeGroundReloadNodeIds_.size()); | ||
| 1001 | +} | ||
| 1002 | + | ||
| 1003 | +void ImageKnifeInternal::ReloadOnForeground() | ||
| 1004 | +{ | ||
| 1005 | + ImageKnifeTrace trace("Reload OnForeground"); | ||
| 1006 | + trace.StartSyncTrace(); | ||
| 1007 | + for (auto &nodeId : onForeGroundReloadNodeIds_) { | ||
| 1008 | + auto it = imageNodeMap_.find(nodeId); | ||
| 1009 | + if (it != imageNodeMap_.end()) { | ||
| 1010 | + it->second->ReloadOnForeground(); | ||
| 1011 | + } | ||
| 1012 | + } | ||
| 1013 | +} | ||
| 1014 | + | ||
| 842 | } // namespace ImageKnifePro | 1015 | } // namespace ImageKnifePro |
| @@ -17,6 +17,7 @@ | |||
| 17 | #define IMAGE_KNIFE_C_KEKE_IMAGEKNIFE_INTERNAL_H | 17 | #define IMAGE_KNIFE_C_KEKE_IMAGEKNIFE_INTERNAL_H |
| 18 | 18 | ||
| 19 | #include <list> | 19 | #include <list> |
| 20 | +#include <unordered_set> | ||
| 20 | #include "callback/load_end_callback.h" | 21 | #include "callback/load_end_callback.h" |
| 21 | #include "dns/dns_dynamic.h" | 22 | #include "dns/dns_dynamic.h" |
| 22 | #include "imageknife.h" | 23 | #include "imageknife.h" |
| @@ -152,7 +153,17 @@ public: | |||
| 152 | void SetJpegOptimizeDecoding(bool enable) override; | 153 | void SetJpegOptimizeDecoding(bool enable) override; |
| 153 | bool GetJpegOptimizeDecoding() const override; | 154 | bool GetJpegOptimizeDecoding() const override; |
| 154 | 155 | ||
| 156 | + void ClearOnBackground(); | ||
| 157 | + void ReloadOnForeground(); | ||
| 155 | private: | 158 | private: |
| 159 | + // 屏幕宽高,每次事件需要重新获取一次,存在折叠屏等屏幕尺寸变换的场景,但不必每次调用重新获取 | ||
| 160 | + int32_t screenWidth_ = 0; | ||
| 161 | + int32_t screenHeight_ = 0; | ||
| 162 | + // 记录重新进入前台时,恢复加载的组件 | ||
| 163 | + std::list<std::string> onForeGroundReloadNodeIds_; | ||
| 164 | + // 记录遍历UI树时,在屏幕范围中的组件,用于退后台时匹配清理组件持有的图片内存 | ||
| 165 | + std::unordered_set<ArkUI_NodeHandle> currentScreenHandles_; | ||
| 166 | + | ||
| 156 | int maxTextureSize_ = 0; | 167 | int maxTextureSize_ = 0; |
| 157 | bool enableJpegOptimiseDecoding_ = false; | 168 | bool enableJpegOptimiseDecoding_ = false; |
| 158 | std::unique_ptr<LoadEndCallback> onLoadEnd_ = nullptr; | 169 | std::unique_ptr<LoadEndCallback> onLoadEnd_ = nullptr; |
| @@ -183,6 +194,10 @@ private: | |||
| 183 | 194 | ||
| 184 | static Rcp_IpAddress *RcpDynamicDnsRuleFunction(const char *host, uint16_t port); | 195 | static Rcp_IpAddress *RcpDynamicDnsRuleFunction(const char *host, uint16_t port); |
| 185 | 196 | ||
| 197 | + void TraversalNode(ArkUI_NodeHandle node, const int32_t &nodeType); | ||
| 198 | + void TraversalNodeCheckChildInScreen(ArkUI_NodeHandle child, const int32_t &parentId, const int32_t &nodeType); | ||
| 199 | + void TraversalChildrenAsExpandMode(ArkUI_NodeHandle node, const int32_t &nodeId); | ||
| 200 | + | ||
| 186 | ~ImageKnifeInternal() override | 201 | ~ImageKnifeInternal() override |
| 187 | { | 202 | { |
| 188 | if (keyPtr_ != nullptr) { | 203 | if (keyPtr_ != nullptr) { |
| @@ -842,6 +842,18 @@ napi_value ImageKnifeNapi::GetJpegOptimizeDecoding(napi_env env, napi_callback_i | |||
| 842 | return result; | 842 | return result; |
| 843 | } | 843 | } |
| 844 | 844 | ||
| 845 | +napi_value ImageKnifeNapi::ClearOnBackground(napi_env env, napi_callback_info info) | ||
| 846 | +{ | ||
| 847 | + ImageKnifeInternal::GetInstance().ClearOnBackground(); | ||
| 848 | + return nullptr; | ||
| 849 | +} | ||
| 850 | + | ||
| 851 | +napi_value ImageKnifeNapi::ReloadOnForeground(napi_env env, napi_callback_info info) | ||
| 852 | +{ | ||
| 853 | + ImageKnifeInternal::GetInstance().ReloadOnForeground(); | ||
| 854 | + return nullptr; | ||
| 855 | +} | ||
| 856 | + | ||
| 845 | napi_value ImageKnifeNapi::RemoveAllMemoryCache(napi_env env, napi_callback_info info) | 857 | napi_value ImageKnifeNapi::RemoveAllMemoryCache(napi_env env, napi_callback_info info) |
| 846 | { | 858 | { |
| 847 | ImageKnife::GetInstance().RemoveAllMemoryCache(); | 859 | ImageKnife::GetInstance().RemoveAllMemoryCache(); |
| @@ -49,6 +49,8 @@ public: | |||
| 49 | nullptr, nullptr, nullptr, napi_default, nullptr}, | 49 | nullptr, nullptr, nullptr, napi_default, nullptr}, |
| 50 | {"getJpegOptimizeDecoding", nullptr, GetJpegOptimizeDecoding, | 50 | {"getJpegOptimizeDecoding", nullptr, GetJpegOptimizeDecoding, |
| 51 | nullptr, nullptr, nullptr, napi_default, nullptr}, | 51 | nullptr, nullptr, nullptr, napi_default, nullptr}, |
| 52 | + {"clearOnBackground", nullptr, ClearOnBackground, nullptr, nullptr, nullptr, napi_default, nullptr}, | ||
| 53 | + {"reloadOnForeground", nullptr, ReloadOnForeground, nullptr, nullptr, nullptr, napi_default, nullptr}, | ||
| 52 | {"getCacheLimitNum", nullptr, GetCacheLimitNum, nullptr, nullptr, nullptr, napi_default, nullptr}, | 54 | {"getCacheLimitNum", nullptr, GetCacheLimitNum, nullptr, nullptr, nullptr, napi_default, nullptr}, |
| 53 | {"getCacheLimitSize", nullptr, GetCacheLimitSize, nullptr, nullptr, nullptr, napi_default, nullptr}, | 55 | {"getCacheLimitSize", nullptr, GetCacheLimitSize, nullptr, nullptr, nullptr, napi_default, nullptr}, |
| 54 | {"getCurrentCacheNum", nullptr, GetCurrentCacheNum, nullptr, nullptr, nullptr, napi_default, nullptr}, | 56 | {"getCurrentCacheNum", nullptr, GetCurrentCacheNum, nullptr, nullptr, nullptr, napi_default, nullptr}, |
| @@ -93,6 +95,8 @@ private: | |||
| 93 | static napi_value SetJpegOptimizeDecoding(napi_env env, napi_callback_info info); | 95 | static napi_value SetJpegOptimizeDecoding(napi_env env, napi_callback_info info); |
| 94 | static napi_value GetJpegOptimizeDecoding(napi_env env, napi_callback_info info); | 96 | static napi_value GetJpegOptimizeDecoding(napi_env env, napi_callback_info info); |
| 95 | static napi_value SetGlobalLoadEndCallback(napi_env env, napi_callback_info info); | 97 | static napi_value SetGlobalLoadEndCallback(napi_env env, napi_callback_info info); |
| 98 | + static napi_value ClearOnBackground(napi_env env, napi_callback_info info); | ||
| 99 | + static napi_value ReloadOnForeground(napi_env env, napi_callback_info info); | ||
| 96 | 100 | ||
| 97 | static napi_value PreCreateNativeNode(napi_env env, napi_callback_info info); | 101 | static napi_value PreCreateNativeNode(napi_env env, napi_callback_info info); |
| 98 | static napi_value ConnectContentSlot(napi_env env, napi_callback_info info); | 102 | static napi_value ConnectContentSlot(napi_env env, napi_callback_info info); |
| @@ -27,7 +27,7 @@ public: | |||
| 27 | virtual ~ArkUINode() = default; | 27 | virtual ~ArkUINode() = default; |
| 28 | protected: | 28 | protected: |
| 29 | ArkUI_NodeHandle handle; | 29 | ArkUI_NodeHandle handle; |
| 30 | - | 30 | +public: |
| 31 | static ArkUI_NativeNodeAPI_1 *GetNodeAPI() | 31 | static ArkUI_NativeNodeAPI_1 *GetNodeAPI() |
| 32 | { | 32 | { |
| 33 | struct NodeAPI { | 33 | struct NodeAPI { |
| @@ -145,6 +145,7 @@ void ImageKnifeNodeCustom::OnDraw(ArkUI_NodeCustomEvent *event) | |||
| 145 | if (needClear_) { | 145 | if (needClear_) { |
| 146 | needClear_ = false; | 146 | needClear_ = false; |
| 147 | IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] Custom Node Clear", GetComponentId().c_str()); | 147 | IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] Custom Node Clear", GetComponentId().c_str()); |
| 148 | + ImageKnifeRender::Clear(event); | ||
| 148 | return; | 149 | return; |
| 149 | } | 150 | } |
| 150 | 151 | ||
| @@ -17,6 +17,7 @@ | |||
| 17 | #include "imageknife_dispatcher.h" | 17 | #include "imageknife_dispatcher.h" |
| 18 | #include "imageknife_internal.h" | 18 | #include "imageknife_internal.h" |
| 19 | #include "imageknife_node_image.h" | 19 | #include "imageknife_node_image.h" |
| 20 | +#include "memory_cache.h" | ||
| 20 | #include "task_worker.h" | 21 | #include "task_worker.h" |
| 21 | #include "utils/imageknife_trace.h" | 22 | #include "utils/imageknife_trace.h" |
| 22 | #include "parser/file_type_parser_default.h" | 23 | #include "parser/file_type_parser_default.h" |
| @@ -284,6 +285,11 @@ void ImageKnifeNodeImage::OnNodeHide() | |||
| 284 | AnimationSwitchToPause(); | 285 | AnimationSwitchToPause(); |
| 285 | } | 286 | } |
| 286 | 287 | ||
| 288 | +void ImageKnifeNodeImage::SetMainDataCache(std::string key) | ||
| 289 | +{ | ||
| 290 | + MemoryCache::GetInstance()->Put(key, mainData_); | ||
| 291 | +} | ||
| 292 | + | ||
| 287 | void ImageKnifeNodeImage::SetDynamicRangeMode(OH_PixelmapNative *pixelmap) | 293 | void ImageKnifeNodeImage::SetDynamicRangeMode(OH_PixelmapNative *pixelmap) |
| 288 | { | 294 | { |
| 289 | auto request = GetImageKnifeRequestInternal(); | 295 | auto request = GetImageKnifeRequestInternal(); |
| @@ -182,6 +182,8 @@ private: | |||
| 182 | void TryUnregisterOnVisibleAreaChange(); | 182 | void TryUnregisterOnVisibleAreaChange(); |
| 183 | 183 | ||
| 184 | void OnDisposeNode(); | 184 | void OnDisposeNode(); |
| 185 | + | ||
| 186 | + void SetMainDataCache(std::string key) final; | ||
| 185 | 187 | ||
| 186 | void OnDerivedNodeEvent(ArkUI_NodeEvent *event) override | 188 | void OnDerivedNodeEvent(ArkUI_NodeEvent *event) override |
| 187 | { | 189 | { |
| @@ -250,7 +252,20 @@ private: | |||
| 250 | // 不能在析构里调该虚函数 | 252 | // 不能在析构里调该虚函数 |
| 251 | void RemoveDisplayedImage() override | 253 | void RemoveDisplayedImage() override |
| 252 | { | 254 | { |
| 253 | - GetNodeAPI()->resetAttribute(handle, NODE_IMAGE_SRC); | 255 | + /** |
| 256 | + * 设置1像素的pixelmap,让组件顶替释放之前pixelmap的引用计数 | ||
| 257 | + * 原因: | ||
| 258 | + * 组件Reset清空显示内容后,仍会持有之前的pixelmap直至组件销毁,导致图片内存无法及时释放 | ||
| 259 | + * 设置pixelmap后立即reset,相当于本次没有设置,仍持有之前的pixelmap | ||
| 260 | + */ | ||
| 261 | + auto data = PixelmapUtils::GetOnePixelDataCache(); | ||
| 262 | + if (data != nullptr && data->GetDrawableDescriptor() != nullptr) { | ||
| 263 | + ArkUI_AttributeItem item = {.object = data->GetDrawableDescriptor()}; | ||
| 264 | + GetNodeAPI()->setAttribute(handle, NODE_IMAGE_SRC, &item); | ||
| 265 | + } else { | ||
| 266 | + // 清空显示的内容,避免组件复用时显示错误的内容 | ||
| 267 | + GetNodeAPI()->resetAttribute(handle, NODE_IMAGE_SRC); | ||
| 268 | + } | ||
| 254 | } | 269 | } |
| 255 | 270 | ||
| 256 | bool IsAnimator() const override | 271 | bool IsAnimator() const override |
| @@ -690,4 +690,56 @@ void ImageKnifeNodeInternal::ApplyAttribute(ImageRequestType type) | |||
| 690 | RemoveResizeableOption(); | 690 | RemoveResizeableOption(); |
| 691 | } | 691 | } |
| 692 | } | 692 | } |
| 693 | + | ||
| 694 | +void ImageKnifeNodeInternal::SetMainDataCache(std::string key) | ||
【AI-Review】【一般】【基础代码问题】【代码逻辑错误】ImageKnifeNodeCustom未覆写SetMainDataCache导致ResumeDataCache无效 ● 问题:基类 ● 影响:一般。虽然 Custom 节点保留了 mainData_ 引用可以正常显示,但内存缓存中没有该图片数据。其他组件查找同一图片时将无法命中缓存,可能导致重复解码。在 ● 建议:在 ![]() ![]() | |||
| 695 | +{ | ||
| 696 | +} | ||
| 697 | + | ||
| 698 | +void ImageKnifeNodeInternal::ResumeDataCache() | ||
| 699 | +{ | ||
| 700 | + if (!mainSrcKey_.empty()) { | ||
| 701 | + SetMainDataCache(mainSrcKey_); | ||
| 702 | + } | ||
| 703 | +} | ||
| 704 | + | ||
| 705 | +bool ImageKnifeNodeInternal::ClearOnBackground() | ||
| 706 | +{ | ||
| 707 | + IMAGE_KNIFE_CHECK_RETURN(imageKnifeRequest_ == nullptr, false); | ||
| 708 | + auto option = imageKnifeRequest_->GetImageKnifeOption(); | ||
| 709 | + IMAGE_KNIFE_CHECK_RETURN(option == nullptr, false); | ||
| 710 | + if (option->loadSrc.GetType() == DataType::PIXELMAP) { | ||
| 711 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] ImageNode Not Clear: Source From Pixelmap", componentId_.c_str()); | ||
| 712 | + return false; | ||
| 713 | + } | ||
| 714 | + | ||
| 715 | + ImageKnifeTrace trace("Clear", componentId_); | ||
| 716 | + trace.StartSyncTrace(); | ||
| 717 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] ImageNode Clear At App OnBackground", componentId_.c_str()); | ||
| 718 | + | ||
| 719 | + ImageKnife::GetInstance().CancelRequest(imageKnifeRequest_); | ||
| 720 | + Clear(); | ||
| 721 | + return true; | ||
| 722 | +} | ||
| 723 | + | ||
| 724 | +void ImageKnifeNodeInternal::ReloadOnForeground() | ||
【AI-Review】【严重】【基础代码问题】【稳定性问题】ReloadOnForeground缺少重新加载失败的错误处理 ● 问题:ReloadOnForeground() 在重新加载图片时,仅创建新请求并通过 Execute() 提交执行,但没有处理加载失败的情况。当图片重新加载失败(如网络不可用、源文件被删除、解码失败等),节点将保持在清除后的空白状态(显示1像素透明图),不会显示错误占位图,也没有重试机制。对比正常的图片加载流程,通常会设置 errorSrc 占位图和重试逻辑,但 ReloadOnForeground() 跳过了这些处理。 ● 影响:严重。应用从后台恢复到前台时,如果图片重新加载失败,用户将看到空白区域而非错误提示,严重影响用户体验。特别是在网络不稳定的环境下,此问题更容易出现。 ● 建议:在 ReloadOnForeground() 中添加错误处理逻辑,至少应包含:1) 创建新请求时确保 errorSrc 占位图生效,确保加载失败时有视觉反馈;2) 考虑添加重试机制(如最多重试3次);3) 在请求中标记来源为前后台切换恢复,便于在 OnImageLoadEnd 回调中区分处理。 ![]() ![]() | |||
| 725 | +{ | ||
| 726 | + ImageKnifeTrace trace("Reload", componentId_); | ||
| 727 | + trace.StartSyncTrace(); | ||
| 728 | + Reuse(); | ||
| 729 | + | ||
| 730 | + IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] ImageNode Reload At App OnForeground", componentId_.c_str()); | ||
| 731 | + IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr); | ||
| 732 | + auto option = imageKnifeRequest_->GetImageKnifeOption(); | ||
| 733 | + IMAGE_KNIFE_CHECK(option == nullptr); | ||
| 734 | + | ||
| 735 | + // 创建新的Request,重新加载 | ||
| 736 | + auto request = std::make_shared<ImageKnifeRequestInternal>(option, componentVersion_); | ||
| 737 | + request->SetComponentId(componentId_); | ||
| 738 | + request->SetComponentSize(GetComponentSize()); | ||
| 739 | + request->SyncLoad(false); | ||
| 740 | + imageKnifeRequest_ = request; | ||
| 741 | + | ||
| 742 | + ImageKnifeInternal::GetInstance().Execute(imageKnifeRequest_); | ||
| 743 | +} | ||
| 744 | + | ||
| 693 | } // end of namespace | 745 | } // end of namespace |
| @@ -184,6 +184,10 @@ public: | |||
| 184 | bool IsDecodeSvgAfterMeasure(std::shared_ptr<ImageKnifeTaskInternal> task); | 184 | bool IsDecodeSvgAfterMeasure(std::shared_ptr<ImageKnifeTaskInternal> task); |
| 185 | 185 | ||
| 186 | bool UploadNodeHandle(); | 186 | bool UploadNodeHandle(); |
| 187 | + | ||
| 188 | + bool ClearOnBackground(); | ||
| 189 | + void ReloadOnForeground(); | ||
| 190 | + void ResumeDataCache(); | ||
| 187 | protected: | 191 | protected: |
| 188 | /** | 192 | /** |
| 189 | * 注册事件,同时绑定事件id,以及ImageKnifeNode | 193 | * 注册事件,同时绑定事件id,以及ImageKnifeNode |
| @@ -278,6 +282,8 @@ private: | |||
| 278 | { | 282 | { |
| 279 | } | 283 | } |
| 280 | 284 | ||
| 285 | + virtual void SetMainDataCache(std::string key); | ||
| 286 | + | ||
| 281 | virtual void SetResizeableOption(std::shared_ptr<ResizableOption> resizeable); | 287 | virtual void SetResizeableOption(std::shared_ptr<ResizableOption> resizeable); |
| 282 | virtual void RemoveResizeableOption(); | 288 | virtual void RemoveResizeableOption(); |
| 283 | 289 | ||
| @@ -34,6 +34,7 @@ | |||
| 34 | #include <native_drawing/drawing_typeface.h> | 34 | #include <native_drawing/drawing_typeface.h> |
| 35 | #include <native_drawing/drawing_types.h> | 35 | #include <native_drawing/drawing_types.h> |
| 36 | #include "number_constant.h" | 36 | #include "number_constant.h" |
| 37 | +#include "image_data_cache_internal.h" | ||
| 37 | 38 | ||
| 38 | namespace ImageKnifePro { | 39 | namespace ImageKnifePro { |
| 39 | 40 | ||
| @@ -104,8 +105,29 @@ static std::map<int, std::function<CalculatePosition(ArkUI_IntSize size, Image_S | |||
| 104 | {ARKUI_OBJECT_FIT_FILL, [](ArkUI_IntSize size, Image_Size imagesize) { return UpdateFill(size, imagesize); }}, | 105 | {ARKUI_OBJECT_FIT_FILL, [](ArkUI_IntSize size, Image_Size imagesize) { return UpdateFill(size, imagesize); }}, |
| 105 | }; | 106 | }; |
| 106 | 107 | ||
| 108 | +/** | ||
| 109 | + * 获取1像素的pixelmap用于clear时在canvas上填充 | ||
| 110 | + * 默认的清理方式只清空显示内容,但仍会持有之前的pixelmap,直到组件销毁或新的pixelmap绘制 | ||
| 111 | + * 1像素pixelmap全局重复使用,无需释放 | ||
| 112 | + */ | ||
| 113 | +OH_Drawing_PixelMap *GetOnePixelDrawingPixelmap() | ||
| 114 | +{ | ||
| 115 | + auto dataCache = PixelmapUtils::GetOnePixelDataCache(); | ||
| 116 | + IMAGE_KNIFE_CHECK_RETURN(dataCache == nullptr, nullptr); | ||
| 117 | + auto imageData = dataCache->GetImageData(); | ||
| 118 | + IMAGE_KNIFE_CHECK_RETURN(imageData == nullptr, nullptr); | ||
| 119 | + OH_Drawing_PixelMap *drawingPixelmap = OH_Drawing_PixelMapGetFromOhPixelMapNative(imageData->GetPixelmap()); | ||
| 120 | + return drawingPixelmap; | ||
| 121 | +} | ||
| 122 | + | ||
| 107 | void ImageKnifeRender::Clear(ArkUI_NodeCustomEvent *event) | 123 | void ImageKnifeRender::Clear(ArkUI_NodeCustomEvent *event) |
| 108 | { | 124 | { |
| 125 | + // 准备1像素pixelmap和对应的绘制区域 | ||
| 126 | + static OH_Drawing_PixelMap *drawingPixelmap = GetOnePixelDrawingPixelmap(); | ||
| 127 | + IMAGE_KNIFE_CHECK(drawingPixelmap == nullptr); | ||
| 128 | + static OH_Drawing_Rect *rectSrc = OH_Drawing_RectCreate(0, 0, 1, 1); | ||
| 129 | + | ||
| 130 | + // 获取canvas,非Create接口创建的,不能调用CanvasDestroy释放 | ||
| 109 | auto drawContext = OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw(event); | 131 | auto drawContext = OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw(event); |
| 110 | auto drawCanvas = reinterpret_cast<OH_Drawing_Canvas *>(OH_ArkUI_DrawContext_GetCanvas(drawContext)); | 132 | auto drawCanvas = reinterpret_cast<OH_Drawing_Canvas *>(OH_ArkUI_DrawContext_GetCanvas(drawContext)); |
| 111 | auto size = OH_ArkUI_DrawContext_GetSize(drawContext); | 133 | auto size = OH_ArkUI_DrawContext_GetSize(drawContext); |
| @@ -113,9 +135,10 @@ void ImageKnifeRender::Clear(ArkUI_NodeCustomEvent *event) | |||
| 113 | IMAGE_KNIFE_LOG(LOG_DEBUG, "Canvas rect width: %{public}d, height: %{public}d", size.width, size.height); | 135 | IMAGE_KNIFE_LOG(LOG_DEBUG, "Canvas rect width: %{public}d, height: %{public}d", size.width, size.height); |
| 114 | auto rectClip = OH_Drawing_RectCreate(0, 0, size.width, size.height); | 136 | auto rectClip = OH_Drawing_RectCreate(0, 0, size.width, size.height); |
【AI-Review】【一般】【基础代码问题】【性能和效率问题】Clear 方法中 OH_Drawing_Rect 重复创建 ● 问题: 更值得关注的是: ● 影响:一般。大量节点清理时可能有轻微性能影响。 ● 建议:考虑将 ![]() ![]() | |||
| 115 | OH_Drawing_CanvasClipRect(drawCanvas, rectClip, INTERSECT, true); | 137 | OH_Drawing_CanvasClipRect(drawCanvas, rectClip, INTERSECT, true); |
| 116 | - OH_Drawing_CanvasClear(drawCanvas, 0); | 138 | + // 绘制填充1像素全透明pixelmap |
| 117 | - // 释放资源 | 139 | + static auto drawOption = OH_Drawing_SamplingOptionsCreate(FILTER_MODE_NEAREST, MIPMAP_MODE_NONE); |
| 118 | - OH_Drawing_CanvasDetachBrush(drawCanvas); | 140 | + OH_Drawing_CanvasDrawPixelMapRect(drawCanvas, drawingPixelmap, rectSrc, rectClip, drawOption); |
| 141 | + | ||
| 119 | OH_Drawing_RectDestroy(rectClip); | 142 | OH_Drawing_RectDestroy(rectClip); |
| 120 | } | 143 | } |
| 121 | 144 | ||
| @@ -226,7 +249,7 @@ void ImageKnifeRender::Drawing(ArkUI_NodeCustomEvent *event, OH_PixelmapNative * | |||
| 226 | CanvasClipRountRect(drawCanvas, borderWidth, size, args); | 249 | CanvasClipRountRect(drawCanvas, borderWidth, size, args); |
| 227 | 250 | ||
| 228 | auto rectCanvas = UpdateImageFit(args, size, imageSize, borderWidth); | 251 | auto rectCanvas = UpdateImageFit(args, size, imageSize, borderWidth); |
| 229 | - OH_Drawing_SamplingOptions *drawOption = OH_Drawing_SamplingOptionsCreate(FILTER_MODE_LINEAR, MIPMAP_MODE_NEAREST); | 252 | + static auto drawOption = OH_Drawing_SamplingOptionsCreate(FILTER_MODE_LINEAR, MIPMAP_MODE_NEAREST); |
| 230 | OH_Drawing_PixelMap *drawingPixmap = OH_Drawing_PixelMapGetFromOhPixelMapNative(data); | 253 | OH_Drawing_PixelMap *drawingPixmap = OH_Drawing_PixelMapGetFromOhPixelMapNative(data); |
| 231 | OH_Drawing_CanvasDrawPixelMapRect(drawCanvas, drawingPixmap, rectSrc, rectCanvas, drawOption); | 254 | OH_Drawing_CanvasDrawPixelMapRect(drawCanvas, drawingPixmap, rectSrc, rectCanvas, drawOption); |
| 232 | 255 | ||
| @@ -73,6 +73,9 @@ export const setJpegOptimizeDecoding:(enable:boolean) => void; | |||
| 73 | export const getJpegOptimizeDecoding:() => boolean; | 73 | export const getJpegOptimizeDecoding:() => boolean; |
| 74 | export const setGlobalLoadEndCallback:(loadEnd:(src:string, requestType:string, isSuccess:boolean, timeInfo?:TimeInfo, | 74 | export const setGlobalLoadEndCallback:(loadEnd:(src:string, requestType:string, isSuccess:boolean, timeInfo?:TimeInfo, |
| 75 | errorCode?:string, errorMessage?:string, requestHeader?:string, responseHeader?:string)=> void) => void; | 75 | errorCode?:string, errorMessage?:string, requestHeader?:string, responseHeader?:string)=> void) => void; |
| 76 | +export const clearOnBackground:() => void; | ||
| 77 | +export const reloadOnForeground:() => void; | ||
| 78 | + | ||
| 76 | export const connectContentSlot: (componentId:string, customId:string, content: Object, | 79 | export const connectContentSlot: (componentId:string, customId:string, content: Object, |
| 77 | imageKnifeOption:ImageKnifeOption | ImageKnifeOptionV2, | 80 | imageKnifeOption:ImageKnifeOption | ImageKnifeOptionV2, |
| 78 | animatorOption: AnimatorOption | AnimatorOptionV2 | undefined, | 81 | animatorOption: AnimatorOption | AnimatorOptionV2 | undefined, |
| @@ -15,6 +15,8 @@ | |||
| 15 | 15 | ||
| 16 | #include "common.h" | 16 | #include "common.h" |
| 17 | #include "log.h" | 17 | #include "log.h" |
| 18 | +#include "api/imageknife_api.h" | ||
| 19 | +#include "arkui_node.h" | ||
| 18 | #include <window_manager/oh_display_manager.h> | 20 | #include <window_manager/oh_display_manager.h> |
| 19 | 21 | ||
| 20 | namespace ImageKnifePro { | 22 | namespace ImageKnifePro { |
| @@ -48,4 +50,21 @@ float PixelToVP(const float &px) | |||
| 48 | return px / density; | 50 | return px / density; |
| 49 | } | 51 | } |
| 50 | 52 | ||
| 53 | +int32_t GetNodeUniqueId(ArkUI_NodeHandle node) | ||
| 54 | +{ | ||
| 55 | + static auto func = ImageKnifeApi::GetInstance().GetArkuiApi().GetApiGetNodeUniqueId(); | ||
| 56 | + if (func != nullptr) { | ||
| 57 | + int32_t uniqueId = -1; | ||
| 58 | + func(node, &uniqueId); | ||
| 59 | + return uniqueId; | ||
| 60 | + } else { | ||
| 61 | + // 低版本Rom使用尚未废弃的方法获取 | ||
| 62 | + auto item = ArkUINode::GetNodeAPI()->getAttribute(node, NODE_UNIQUE_ID); | ||
| 63 | + if (item != nullptr && item->size > 0) { | ||
| 64 | + return item->value[0].i32; | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | + return -1; | ||
| 68 | +} | ||
| 69 | + | ||
| 51 | } // namespace ImageKnifePro | 70 | } // namespace ImageKnifePro |
| @@ -16,6 +16,7 @@ | |||
| 16 | #ifndef IMAGEKNIFEPRO_COMMON_H | 16 | #ifndef IMAGEKNIFEPRO_COMMON_H |
| 17 | #define IMAGEKNIFEPRO_COMMON_H | 17 | #define IMAGEKNIFEPRO_COMMON_H |
| 18 | 18 | ||
| 19 | +#include <arkui/native_node.h> | ||
| 19 | namespace ImageKnifePro { | 20 | namespace ImageKnifePro { |
| 20 | 21 | ||
| 21 | const char *GetImageKnifeVersion(); | 22 | const char *GetImageKnifeVersion(); |
| @@ -27,6 +28,8 @@ float GetDisplayDensity(); | |||
| 27 | 28 | ||
| 28 | float PixelToVP(const float &px); | 29 | float PixelToVP(const float &px); |
| 29 | 30 | ||
| 31 | +int32_t GetNodeUniqueId(ArkUI_NodeHandle node); | ||
| 32 | + | ||
| 30 | } // namespace ImageKnifePro | 33 | } // namespace ImageKnifePro |
| 31 | 34 | ||
| 32 | #endif // IMAGEKNIFEPRO_COMMON_H | 35 | #endif // IMAGEKNIFEPRO_COMMON_H |
| @@ -15,6 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | #include "pixelmap_utils.h" | 16 | #include "pixelmap_utils.h" |
| 17 | #include "api/imageknife_api.h" | 17 | #include "api/imageknife_api.h" |
| 18 | +#include "image_data_cache_internal.h" | ||
| 18 | 19 | ||
| 19 | namespace ImageKnifePro { | 20 | namespace ImageKnifePro { |
| 20 | 21 | ||
| @@ -40,5 +41,41 @@ void PixelmapUtils::SetMemoryName(std::shared_ptr<ImageData> data, std::string n | |||
| 40 | apiFunc(pixelmapList[i], &name[0], &length); | 41 | apiFunc(pixelmapList[i], &name[0], &length); |
| 41 | } | 42 | } |
| 42 | } | 43 | } |
| 44 | + | ||
| 45 | +std::shared_ptr<ImageDataCacheInternal> CreateOnePixelData() | ||
| 46 | +{ | ||
| 47 | + OH_Pixelmap_InitializationOptions *options = nullptr; | ||
| 48 | + Image_ErrorCode errorCode = OH_PixelmapInitializationOptions_Create(&options); | ||
| 49 | + if (errorCode != IMAGE_SUCCESS) { | ||
| 50 | + IMAGE_KNIFE_LOG(LOG_ERROR, "Create Pixelmap Initialization Options Failed:%{public}d", errorCode); | ||
| 51 | + return nullptr; | ||
| 52 | + } | ||
| 53 | + OH_PixelmapInitializationOptions_SetWidth(options, 1); | ||
| 54 | + OH_PixelmapInitializationOptions_SetHeight(options, 1); | ||
| 55 | + OH_PixelmapInitializationOptions_SetPixelFormat(options, PIXEL_FORMAT_RGBA_8888); | ||
| 56 | + OH_PixelmapInitializationOptions_SetSrcPixelFormat(options, PIXEL_FORMAT_RGBA_8888); | ||
| 57 | + | ||
| 58 | + constexpr int bufferSize = 4; | ||
| 59 | + constexpr int value = 255; | ||
| 60 | + uint8_t buffer[bufferSize] = {value, value, value, 0}; // 1像素白色完全透明buffer | ||
| 61 | + OH_PixelmapNative *pixelmap = nullptr; | ||
| 62 | + errorCode = OH_PixelmapNative_CreatePixelmap(buffer, bufferSize, options, &pixelmap); | ||
| 63 | + OH_PixelmapInitializationOptions_Release(options); | ||
| 64 | + if (errorCode != IMAGE_SUCCESS) { | ||
| 65 | + IMAGE_KNIFE_LOG(LOG_ERROR, "Create Pixelmap Failed:%{public}d", errorCode); | ||
| 66 | + return nullptr; | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + auto data = std::make_shared<ImageDataCacheInternal>(pixelmap); | ||
| 70 | + PixelmapUtils::SetMemoryName(data->GetImageData(), "ImageKnifePro_1_pixel"); | ||
| 71 | + return data; | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +std::shared_ptr<ImageDataCacheInternal> PixelmapUtils::GetOnePixelDataCache() | ||
| 75 | +{ | ||
| 76 | + static auto dataCache = CreateOnePixelData(); | ||
| 77 | + return dataCache; | ||
| 78 | +} | ||
| 79 | + | ||
| 43 | } | 80 | } |
| 44 | 81 | ||
| @@ -20,10 +20,17 @@ | |||
| 20 | #include "image_data.h" | 20 | #include "image_data.h" |
| 21 | 21 | ||
| 22 | namespace ImageKnifePro { | 22 | namespace ImageKnifePro { |
| 23 | +class ImageDataCacheInternal; | ||
| 23 | 24 | ||
| 24 | class PixelmapUtils { | 25 | class PixelmapUtils { |
| 25 | public: | 26 | public: |
| 26 | static void SetMemoryName(std::shared_ptr<ImageData> data, std::string name); | 27 | static void SetMemoryName(std::shared_ptr<ImageData> data, std::string name); |
| 28 | + | ||
| 29 | + /** | ||
| 30 | + * @brief 获取1像素的pixelmap的缓存对象,该pixelmap不会重复创建 | ||
| 31 | + * @return 返回ImageDataCacheInternal指针 | ||
| 32 | + */ | ||
| 33 | + static std::shared_ptr<ImageDataCacheInternal> GetOnePixelDataCache(); | ||
| 27 | 34 | ||
| 28 | static Image_Size GetImageSize(OH_PixelmapNative *data) | 35 | static Image_Size GetImageSize(OH_PixelmapNative *data) |
| 29 | { | 36 | { |
| @@ -342,6 +342,24 @@ export class ImageKnife { | |||
| 342 | nativeNode.deleteHeader(key); | 342 | nativeNode.deleteHeader(key); |
| 343 | } | 343 | } |
| 344 | 344 | ||
| 345 | + /** | ||
| 346 | + * 清除所有内存缓存,保留当前页面在屏幕范围内的组件图片内存,清除其余所有ImageKnife组件所持有的图片内存,以减少应用退后台后的内存占用 | ||
| 347 | + * 可以在EntryAbility的onBackground回调中调用 | ||
| 348 | + * 需要配和reloadOnForeground使用 | ||
| 349 | + */ | ||
| 350 | + clearOnBackground() { | ||
| 351 | + nativeNode.clearOnBackground(); | ||
| 352 | + } | ||
| 353 | + | ||
| 354 | + /** | ||
| 355 | + * 在应用切换至前台时重新加载被清空的组件图片 | ||
| 356 | + * 可以在EntryAbility的onForeground回调中调用 | ||
| 357 | + * 需要配和clearOnBackground使用 | ||
| 358 | + */ | ||
| 359 | + reloadOnForeground() { | ||
| 360 | + nativeNode.reloadOnForeground(); | ||
| 361 | + } | ||
| 362 | + | ||
| 345 | /** | 363 | /** |
| 346 | * 清除所有内存缓存 | 364 | * 清除所有内存缓存 |
| 347 | */ | 365 | */ |


【AI-Review】【一般】【基础代码问题】【稳定性问题】ClearOnBackground使用节点handle前未验证有效性
● 问题:ImageKnifeInternal::ClearOnBackground() 中直接通过 node->GetHandle() 获取 ArkUI 节点句柄,然后调用 OH_ArkUI_GetRouterPageState(handle, &state)。但代码没有验证 handle 是否仍然有效。如果某个节点的原生 ArkUI 节点已经被框架回收(例如页面已销毁、组件已卸载),但该节点尚未从 imageNodeMap_ 中移除,传入无效的 handle 给 OH_ArkUI_GetRouterPageState 可能导致未定义行为或崩溃。
● 影响:一般。在正常流程中,DisposeImageNode 应该在节点销毁时被调用以从 imageNodeMap_ 中移除节点。但如果存在时序问题(如 ArkUI 框架先回收节点,后触发回调),则可能出现 handle 无效的情况。
● 建议:在调用 OH_ArkUI_GetRouterPageState 之前,增加对 handle 有效性的检查,或者对该调用增加错误码判断后的保护逻辑:1) 检查 handle 是否为 nullptr;2) 当 OH_ArkUI_GetRouterPageState 返回错误码时,按非当前页面处理该节点(即执行 ClearOnBackground 清理)。