1/* 2 * Copyright (c) 2025 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// [Start example_pass_obj] 17import { taskpool } from '@kit.ArkTS'; 18import { loadPixelMap } from './pixelMapTest'; 19import { BusinessError } from '@kit.BasicServicesKit'; 20 21@Entry 22@Component 23struct Index { 24 @State message: string = 'Hello World'; 25 @State pixelMap: PixelMap | undefined = undefined; 26 27 private loadImageFromThread(): void { 28 const resourceMgr = getContext(this).resourceManager; 29 // 此处‘startIcon.png’为media下复制到rawfile文件夹中,请开发者自行替换,否则imageSource创建失败会导致后续无法正常执行。 30 resourceMgr.getRawFd('startIcon.png').then(rawFileDescriptor => { 31 taskpool.execute(loadPixelMap, rawFileDescriptor).then(pixelMap => { 32 if (pixelMap) { 33 this.pixelMap = pixelMap as PixelMap; 34 console.log('Succeeded in creating pixelMap.'); 35 // 主线程释放pixelMap。由于子线程返回pixelMap时已调用setTransferDetached,所以此处能够立即释放pixelMap。 36 this.pixelMap.release(); 37 } else { 38 console.error('Failed to create pixelMap.'); 39 } 40 }).catch((e: BusinessError) => { 41 console.error('taskpool execute loadPixelMap failed. Code: ' + e.code + ', message: ' + e.message); 42 }); 43 }); 44 } 45 46 build() { 47 RelativeContainer() { 48 Text(this.message) 49 .id('HelloWorld') 50 .fontSize(50) 51 .fontWeight(FontWeight.Bold) 52 .alignRules({ 53 center: { anchor: '__container__', align: VerticalAlign.Center }, 54 middle: { anchor: '__container__', align: HorizontalAlign.Center } 55 }) 56 .onClick(() => { 57 this.loadImageFromThread(); 58 this.message = 'success'; 59 }) 60 } 61 .height('100%') 62 .width('100%') 63 } 64} 65// [End example_pass_obj] 66 67