2 回复
XComponent组件作为一种绘制组件,通常用于满足用户复杂的自定义绘制需求,其主要有两种类型"surface和component。对于surface类型可以将相关数据传入XComponent单独拥有的NativeWindow来渲染画面。 示例:图像AI分析功能使用示例
// xxx.ets
import { BusinessError } from '@kit.BasicServicesKit';
import nativeRender from 'libnativerender.so';
class CustomXComponentController extends XComponentController {
onSurfaceCreated(surfaceId: string): void {
console.log(`onSurfaceCreated surfaceId: ${surfaceId}`);
nativeRender.SetSurfaceId(BigInt(surfaceId));
}
onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void {
console.log(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`);
nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight);
}
onSurfaceDestroyed(surfaceId: string): void {
console.log(`onSurfaceDestroyed surfaceId: ${surfaceId}`);
nativeRender.DestroySurface(BigInt(surfaceId));
}
}
@Entry
@Component
struct XComponentExample {
xComponentController: XComponentController = new CustomXComponentController();
private config: ImageAnalyzerConfig = {
types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT]
};
private aiController: ImageAnalyzerController = new ImageAnalyzerController();
private options: ImageAIOptions = {
types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
aiController: this.aiController
};
@State xcWidth: string = "320px";
@State xcHeight: string = "480px";
@State currentStatus: string = "index";
build() {
Column({ space: 5 }) {
Button("change size")
.onClick(() => {
this.xcWidth = "640px";
this.xcHeight = "720px";
})
Button('start AI analyze')
.onClick(() => {
this.xComponentController.startImageAnalyzer(this.config);
.then(() => {
console.log("analysis complete");
})
.catch((error: BusinessError) => {
console.log("error code: " + error.code);
})
})
Button('stop AI analyze')
.onClick(() => {
this.xComponentController.stopImageAnalyzer();
})
Button('get analyzer types')
.onClick(() => {
this.aiController.getImageAnalyzerSupportTypes();
})
Button('Draw Star')
.fontSize('16fp')
.fontWeight(500)
.margin({ bottom: 24 })
.onClick(() => {
let surfaceId = this.xComponentController.getXComponentSurfaceId();
this.xComponentController.getXComponentSurfaceRect();
nativeRender.DrawPattern(BigInt(surfaceId));
let hasDraw: boolean = false;
if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) {
hasDraw = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasDraw;
}
if (hasDraw) {
this.currentStatus = "draw star";
}
})
XComponent({
type: XComponentType.SURFACE,
controller: this.xComponentController,
imageAIOptions: this.options
})
.width(this.xcWidth)
.height(this.xcHeight)
.enableAnalyzer(true)
Test(this.currentStatus)
.fontSize('24fp')
.fontWeight(500)
}
.width("100%")
}
}