跳到主要内容

画布

Canvas 组件是您的 Skia 绘图的根。您可以将其视为常规的 React Native 视图并分配视图样式。在后台,它使用自己的 React 渲染器。

名称类型描述。
style?ViewStyle视图样式
ref?Ref<SkiaView>SkiaView 对象的引用
opaque?boolean默认情况下,画布是透明的,但在 Android 上,您可以使其不透明以提高性能。
onSize?SharedValue<Size>Reanimated 值,画布大小将分配给该值(请参阅 画布大小
onLayout?NativeEvent<LayoutEvent>在挂载和布局更改时调用(请参阅 onLayout

获取画布大小

如果画布的大小未知,有两种方法可以访问它

  • 在 JS 线程上,使用 onLayout 属性,就像您在任何常规 React Native 视图上一样。
  • 在 UI 线程上,使用 onSize 属性和 Reanimated

获取画布快照

您可以使用 makeImageSnapshotAsync 方法将您的绘图保存为图像。此方法返回一个 Promise,该 Promise 解析为 图像。它在 UI 线程上执行,确保可以访问与屏幕上画布相同的 Skia 上下文,包括 纹理

如果您的绘图不包含纹理,为了简单起见,您也可以使用同步的 makeImageSnapshot 方法。

示例

tsx
import {useEffect} from "react";
import {Canvas, useCanvasRef, Circle} from "@shopify/react-native-skia";
 
export const Demo = () => {
const ref = useCanvasRef();
useEffect(() => {
setTimeout(() => {
// you can pass an optional rectangle
// to only save part of the image
const image = ref.current?.makeImageSnapshot();
if (image) {
// you can use image in an <Image> component
// Or save to file using encodeToBytes -> Uint8Array
const bytes = image.encodeToBytes();
}
}, 1000)
});
return (
<Canvas style={{ flex: 1 }} ref={ref}>
<Circle r={128} cx={128} cy={128} color="red" />
</Canvas>
);
};
tsx
import {useEffect} from "react";
import {Canvas, useCanvasRef, Circle} from "@shopify/react-native-skia";
 
export const Demo = () => {
const ref = useCanvasRef();
useEffect(() => {
setTimeout(() => {
// you can pass an optional rectangle
// to only save part of the image
const image = ref.current?.makeImageSnapshot();
if (image) {
// you can use image in an <Image> component
// Or save to file using encodeToBytes -> Uint8Array
const bytes = image.encodeToBytes();
}
}, 1000)
});
return (
<Canvas style={{ flex: 1 }} ref={ref}>
<Circle r={128} cx={128} cy={128} color="red" />
</Canvas>
);
};

可访问性

Canvas 组件支持与 View 组件相同的属性,包括其 辅助功能属性。您还可以通过在画布顶部覆盖视图来使画布内的元素可访问。这与 在特定画布元素上应用手势 使用的方法相同。