#鸿蒙通关秘籍#如何跨线程传递鸿蒙系统中的PixelMap对象?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
墨染流年NAT

可以通过转移方式跨线程传递PixelMap对象,因其本质上是NativeBinding对象。在子线程中创建PixelMap对象并将其传递给主线程,确保在调用setTransferDetached(true)以断开原线程对该对象的引用。

typescript // Index.ets import { taskpool } from '@kit.ArkTS'; import { loadPixelMap } from './pixelMapTest'; import { BusinessError } from '@kit.BasicServicesKit';

@Entry @Component struct Index { @State message: string = 'Hello World'; @State pixelMap: PixelMap | undefined = undefined;

private loadImageFromThread(): void { const resourceMgr = getContext(this).resourceManager; resourceMgr.getRawFd('startIcon.png').then(rawFileDescriptor => { taskpool.execute(loadPixelMap, rawFileDescriptor).then(pixelMap => { if (pixelMap) { this.pixelMap = pixelMap as PixelMap; console.log('Succeeded in creating pixelMap.'); this.pixelMap.release(); } else { console.error('Failed to create pixelMap.'); } }).catch((e: BusinessError) => { console.error('taskpool execute loadPixelMap failed. Code: ' + e.code + ', message: ' + e.message); }); }); }

build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) .onClick(() => { this.loadImageFromThread(); }) } .height('100%') .width('100%') } }

typescript // pixelMapTest.ets import { image } from '@kit.ImageKit';

@Concurrent export async function loadPixelMap(rawFileDescriptor: number): Promise<PixelMap> { const imageSource = image.createImageSource(rawFileDescriptor); const pixelMap = imageSource.createPixelMapSync(); imageSource.release(); pixelMap.setTransferDetached(true); return pixelMap; }

分享
微博
QQ
微信
回复
2天前
相关问题
是否支持Context线程传递
1857浏览 • 1回复 待解决