Add example app and fix Android asset loading on image switch.

Introduce the example integration demo, export resolveAssetPath, harden resolveImageUrl for Android bundled assets, and update gitignore to exclude example build outputs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
a1518 2026-06-30 20:24:43 -07:00
parent 56738b1f06
commit eb246efa8a
71 changed files with 9348 additions and 36 deletions

22
.gitignore vendored
View File

@ -73,3 +73,25 @@ yarn-error.log
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Example app (monorepo integration demo)
example/node_modules/
example/android/.gradle/
example/android/app/.cxx/
example/android/app/build/
example/android/build/
example/ios/Pods/
example/ios/build/
example/ios/DerivedData/
# IDE / editor
.cursor/
.idea/
*.swp
*~
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -57,9 +57,9 @@ cd ios && pod install && cd ..
确保宿主已按各原生库文档完成 Skia、Reanimated、OpenCV 等配置。
### Metro 配置npm link 时)
### Metro 配置npm link / monorepo / file: 依赖时)
联调时若出现模块解析问题,在宿主 `metro.config.js` 中把本库加入 `watchFolders` / `extraNodeModules`(按宿主 Metro 版本调整)
联调时若出现模块解析问题,在宿主 `metro.config.js` 中把本库加入 `watchFolders`,并使用下面推荐的完整配置(同时包含 extraNodeModules + blockList。这是防止所有「类似重复模块问题」SkiaPictureView undefined、Reanimated Animated node already exists 等)的可靠做法
```js
const path = require('path');
@ -68,10 +68,51 @@ module.exports = {
watchFolders: [path.resolve(__dirname, '../MaskSegmentApp')],
resolver: {
nodeModulesPaths: [path.resolve(__dirname, 'node_modules')],
// 推荐同时使用 extraNodeModules + blockList
extraNodeModules: {
'react-native-reanimated': path.resolve(__dirname, 'node_modules/react-native-reanimated'),
'@shopify/react-native-skia': path.resolve(__dirname, 'node_modules/@shopify/react-native-skia'),
'react-native-gesture-handler': path.resolve(__dirname, 'node_modules/react-native-gesture-handler'),
'react-native-fast-opencv': path.resolve(__dirname, 'node_modules/react-native-fast-opencv'),
'react-native-safe-area-context': path.resolve(__dirname, 'node_modules/react-native-safe-area-context'),
'react-native-fs': path.resolve(__dirname, 'node_modules/react-native-fs'),
},
blockList: [
/\/MaskSegmentApp\/node_modules\/@shopify\/react-native-skia\//,
/\/MaskSegmentApp\/node_modules\/react-native-reanimated\//,
/\/MaskSegmentApp\/node_modules\/react-native-fast-opencv\//,
/\/MaskSegmentApp\/node_modules\/react-native-gesture-handler\//,
/\/MaskSegmentApp\/node_modules\/react-native-safe-area-context\//,
/\/MaskSegmentApp\/node_modules\/react-native-fs\//,
],
},
};
```
**强烈建议**在宿主 `index.js` 最顶部加入(在任何业务代码之前):
```js
import '@shopify/react-native-skia';
```
(完整推荐配置见下文「故障排查」以及 `example/metro.config.js` + `example/index.js`,那里有覆盖全部 peer 的 singletons 列表。)
### 故障排查:各种重复模块导致的运行时错误
常见症状(同类问题):
- `SkiaPictureView must be a function (received 'undefined')`
- `createAnimatedNode: Animated node[...] already exists`
**几乎总是**因为 Metro 同时解析到多份 reanimated / skia / gesture-handler / fast-opencv / safe-area 等包。
**最佳实践**
- 直接复制 `example/metro.config.js` 里的 `singletonPackages` + extraNodeModules + blockList 写法
- 在你的 `index.js` 最顶部加入 gesture-handler → reanimated → skia 三个 import
- 重启 Metro (`--reset-cache`) + 重装 app
详细清单和模板见 `example/README.md` 的「运行时出现类似错误」一节。
### 业务侧引入
```tsx

View File

@ -1 +1 @@
{"version":3,"file":"MaskSegmentCanvas.d.ts","sourceRoot":"","sources":["../../src/components/MaskSegmentCanvas.tsx"],"names":[],"mappings":"AAAA,OAAO,KAQN,MAAM,OAAO,CAAC;AAmDf,OAAO,KAAK,EAEV,sBAAsB,EACtB,oBAAoB,EAMrB,MAAM,2BAA2B,CAAC;AAcnC,YAAY,EACV,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,QAAQ,EACR,iBAAiB,GAClB,MAAM,2BAA2B,CAAC;AA4ZnC,QAAA,MAAM,iBAAiB,qGA2pErB,CAAC;AA8HH,eAAe,iBAAiB,CAAC"}
{"version":3,"file":"MaskSegmentCanvas.d.ts","sourceRoot":"","sources":["../../src/components/MaskSegmentCanvas.tsx"],"names":[],"mappings":"AAAA,OAAO,KAQN,MAAM,OAAO,CAAC;AAmDf,OAAO,KAAK,EAEV,sBAAsB,EACtB,oBAAoB,EAMrB,MAAM,2BAA2B,CAAC;AAcnC,YAAY,EACV,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,QAAQ,EACR,iBAAiB,GAClB,MAAM,2BAA2B,CAAC;AA4ZnC,QAAA,MAAM,iBAAiB,qGAoqErB,CAAC;AA8HH,eAAe,iBAAiB,CAAC"}

View File

@ -7,7 +7,7 @@ import { launchImageLibrary } from 'react-native-image-picker';
import cv from '../utils/opencvAdapter';
import { buildAllRegionOutlinePaths, buildRegionOutlinePathForRegion, downsampleMaskDataForPaths, extractRegionsFromMaskBufferSync, isBaseboardMaskPixel, upscaleBinaryMask, } from '../utils/maskSegmentation';
import { clearDerivedImageCache, readPngBgrBuffer, prewarmPngBgrCache, resizeBgrBuffer, } from '../utils/pngImage';
import { resolveImageUrl } from '../utils/resolveImageUrl';
import { hashUrl, resolveImageUrl } from '../utils/resolveImageUrl';
import { compositePaintedImage } from '../utils/compositePaintedImage';
import { paintedRegionsFingerprint, resolveExportResultForDestDir, } from '../utils/exportUtils';
import { preparePaintResourcesFromWorkBuffer, releaseFreqLayerImages, } from '../utils/freqLayerPrep';
@ -408,8 +408,8 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
void (async () => {
try {
const [originPath, maskPath] = await Promise.all([
resolveImageUrl(originSource, 'origin.png'),
resolveImageUrl(maskSource, 'mask.png'),
resolveImageUrl(originSource, `origin_${hashUrl(originSource)}.png`),
resolveImageUrl(maskSource, `mask_${hashUrl(maskSource)}.png`),
]);
if (!cancelled) {
setResolvedOriginPath(originPath);
@ -902,7 +902,10 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
}
}, [emitWatch, emitInteractiveIfReady, emitMaskPathsReadyIfReady, reportError]);
const loadPaintLayersIfNeeded = useCallback(() => {
if (paintResourcesReady) {
// Use the ref (synced in segmentAndPrepareLayers cleanup) rather than
// paintResourcesReady state — after switching origin/mask URLs the state
// may still read true for one frame while layers were already released.
if (paintResourceLayersRef.current) {
return Promise.resolve();
}
if (paintLayersPromiseRef.current) {
@ -964,7 +967,7 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
})();
paintLayersPromiseRef.current = promise;
return promise;
}, [emitInteractiveIfReady, paintResourcesReady]);
}, [emitInteractiveIfReady]);
loadPaintLayersRef.current = loadPaintLayersIfNeeded;
const pickOriginImage = async () => {
const res = await launchImageLibrary({ mediaType: 'photo' });
@ -1389,8 +1392,12 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
// Stable refs for functions called inside gesture closures
const findRegionAtPointRef = useRef(findRegionAtPoint);
const onCanvasTapRef = useRef(onCanvasTap);
const onUserInteractionRef = useRef(onUserInteraction);
const resetZoomRef = useRef(resetZoom);
useEffect(() => { findRegionAtPointRef.current = findRegionAtPoint; }, [findRegionAtPoint]);
useEffect(() => { onCanvasTapRef.current = onCanvasTap; }, [onCanvasTap]);
useEffect(() => { onUserInteractionRef.current = onUserInteraction; }, [onUserInteraction]);
useEffect(() => { resetZoomRef.current = resetZoom; }, [resetZoom]);
const undoSelection = useCallback(() => {
onUserInteraction();
setPaintHistory(history => {
@ -1733,7 +1740,7 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
// Immediate hold highlight — fires on touch-down regardless of brush state.
// When a brush is active, this lets the user preview which region they're
// about to paint before lifting their finger.
onUserInteraction();
onUserInteractionRef.current?.();
const coords = screenToCanvasCoords(x, y, canvasWRef.current, canvasHRef.current, zoomScaleRef.current, panOffsetRef.current);
const regionId = findRegionAtPointRef.current(coords.x, coords.y, true);
if (regionId == null || !imageSizeRef2.current) {
@ -1799,7 +1806,7 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
'worklet';
runOnJS(onFinalizeJS)(e.x, e.y);
});
}, [onUserInteraction]);
}, []);
// ── Gesture: pinch-zoom (two-finger scale; max 5×) ─────────────────────
const pinchGesture = useMemo(() => {
const onStartJS = () => {
@ -1817,7 +1824,7 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
};
const onEndJS = () => {
if (zoomScaleRef.current <= 1.01) {
resetZoom();
resetZoomRef.current?.();
}
};
return Gesture.Pinch()
@ -1833,9 +1840,11 @@ const MaskSegmentCanvas = forwardRef(function MaskSegmentCanvas(props, ref) {
'worklet';
runOnJS(onEndJS)();
});
}, [resetZoom]);
}, []);
// ── Composed: Race ensures single-tap and pinch-zoom never conflict ─────────
const composedGesture = useMemo(() => Gesture.Race(tapGesture, pinchGesture), [tapGesture, pinchGesture]);
// 依赖置空 + 内部的 tap/pinch 也用 [],保证整个手势描述符树只在 mount 时创建一次。
// 避免初始化阶段反复创建导致 Reanimated / RNGH 内部节点重复分配。
const composedGesture = useMemo(() => Gesture.Race(tapGesture, pinchGesture), []);
return (_jsxs(View, { style: [styles.container, style], onLayout: (e) => {
const { width, height } = e.nativeEvent.layout;
setLayoutWidth(width);

File diff suppressed because one or more lines are too long

1
dist/index.d.ts vendored
View File

@ -3,4 +3,5 @@ export type { BgrColor, InteractionConfig, MaskSegmentCanvasProps, MaskSegmentCa
export { BASEBOARD_SEMANTIC_NAME, MASK_SEMANTIC_COLORS, } from './utils/maskSemanticPalette';
export { createRuntimeConfig, DEFAULT_INTERACTION_CONFIG, DEFAULT_MASK_CONFIG, DEFAULT_PAINT_CONFIG, DEFAULT_PIPELINE_CONFIG, PIPELINE_HIGH, PIPELINE_LOW, PIPELINE_MEDIUM, PIPELINE_PRESETS, getMaskSegmentRuntimeConfig, resolvePipelineConfig, setMaskSegmentRuntimeConfig, } from './utils/maskSegmentRuntime';
export { prewarmPngBgrCache, prewarmPngBgrCacheAsync, } from './utils/pngImage';
export { resolveAssetPath } from './utils/resolveAssetPath';
//# sourceMappingURL=index.d.ts.map

2
dist/index.d.ts.map vendored
View File

@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AACzD,YAAY,EACV,QAAQ,EACR,iBAAiB,EACjB,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,EACxB,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,aAAa,GACd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,aAAa,EACb,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,2BAA2B,EAC3B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC"}
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AACzD,YAAY,EACV,QAAQ,EACR,iBAAiB,EACjB,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,EACxB,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,aAAa,GACd,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,aAAa,EACb,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,2BAA2B,EAC3B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC"}

1
dist/index.js vendored
View File

@ -2,4 +2,5 @@ export { default } from './components/MaskSegmentCanvas';
export { BASEBOARD_SEMANTIC_NAME, MASK_SEMANTIC_COLORS, } from './utils/maskSemanticPalette';
export { createRuntimeConfig, DEFAULT_INTERACTION_CONFIG, DEFAULT_MASK_CONFIG, DEFAULT_PAINT_CONFIG, DEFAULT_PIPELINE_CONFIG, PIPELINE_HIGH, PIPELINE_LOW, PIPELINE_MEDIUM, PIPELINE_PRESETS, getMaskSegmentRuntimeConfig, resolvePipelineConfig, setMaskSegmentRuntimeConfig, } from './utils/maskSegmentRuntime';
export { prewarmPngBgrCache, prewarmPngBgrCacheAsync, } from './utils/pngImage';
export { resolveAssetPath } from './utils/resolveAssetPath';
//# sourceMappingURL=index.js.map

2
dist/index.js.map vendored
View File

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAuBzD,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,aAAa,EACb,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,2BAA2B,EAC3B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAuBzD,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,aAAa,EACb,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,2BAA2B,EAC3B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC"}

View File

@ -1,3 +1,4 @@
export declare function hashUrl(url: string): string;
/** 将本地路径或远程 URL 解析为 OpenCV / RNFS 可读的 PNG 本地路径 */
export declare function resolveImageUrl(source: string, cacheFileName?: string): Promise<string>;
//# sourceMappingURL=resolveImageUrl.d.ts.map

View File

@ -1 +1 @@
{"version":3,"file":"resolveImageUrl.d.ts","sourceRoot":"","sources":["../../src/utils/resolveImageUrl.ts"],"names":[],"mappings":"AAYA,kDAAkD;AAClD,wBAAsB,eAAe,CACnC,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,MAAM,CAAC,CA8CjB"}
{"version":3,"file":"resolveImageUrl.d.ts","sourceRoot":"","sources":["../../src/utils/resolveImageUrl.ts"],"names":[],"mappings":"AAIA,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAM3C;AAED,kDAAkD;AAClD,wBAAsB,eAAe,CACnC,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,MAAM,CAAC,CAiEjB"}

View File

@ -1,7 +1,7 @@
import { Platform } from 'react-native';
import RNFS from 'react-native-fs';
import { ensurePngFile, isPngPath, normalizePath, toPngFileName } from './pngImage';
function hashUrl(url) {
export function hashUrl(url) {
let hash = 0;
for (let i = 0; i < url.length; i++) {
hash = (hash * 31 + url.charCodeAt(i)) | 0;
@ -46,6 +46,25 @@ export async function resolveImageUrl(source, cacheFileName) {
if (await RNFS.exists(normalized)) {
return ensurePngFile(normalized, pngCacheName);
}
// Android bundled assets: resolveAssetSource may yield asset:/ or
// file:///android_asset/ URIs that RNFS cannot read directly.
if (Platform.OS === 'android') {
const assetPath = trimmed
.replace(/^asset:\/?\/?/, '')
.replace(/^file:\/\/\/android_asset\//, '');
if (assetPath !== trimmed) {
const tmpDest = `${RNFS.CachesDirectoryPath}/tmp_${Date.now()}_${pngCacheName}`;
await RNFS.copyFileAssets(assetPath, tmpDest);
try {
return await ensurePngFile(tmpDest, pngCacheName);
}
finally {
if (await RNFS.exists(tmpDest)) {
await RNFS.unlink(tmpDest);
}
}
}
}
return ensurePngFile(trimmed, pngCacheName);
}
//# sourceMappingURL=resolveImageUrl.js.map

View File

@ -1 +1 @@
{"version":3,"file":"resolveImageUrl.js","sourceRoot":"","sources":["../../src/utils/resolveImageUrl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,IAAI,MAAM,iBAAiB,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEpF,SAAS,OAAO,CAAC,GAAW;IAC1B,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAI,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC5C;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACrC,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAc,EACd,aAAsB;IAEtB,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;IAED,MAAM,YAAY,GAAG,aAAa,CAChC,aAAa,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAC/C,CAAC;IAEF,IAAI,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE;QACnE,MAAM,OAAO,GAAG,GAAG,IAAI,CAAC,mBAAmB,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,YAAY,EAAE,CAAC;QAChF,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC;YAC7C,OAAO,EAAE,OAAO;YAChB,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC,OAAO,CAAC;QACX,IAAI,UAAU,KAAK,GAAG,EAAE;YACtB,MAAM,IAAI,KAAK,CAAC,0BAA0B,OAAO,EAAE,CAAC,CAAC;SACtD;QACD,IAAI;YACF,OAAO,MAAM,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;SACnD;gBAAS;YACR,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE;gBAC9B,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;aAC5B;SACF;KACF;IAED,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE;QAC1D,OAAO,UAAU,CAAC;KACnB;IAED,IAAI,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;QACpC,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,IAAI,QAAQ,CAAC,EAAE,KAAK,KAAK,IAAI,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QACvD,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE;QACjC,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,OAAO,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC9C,CAAC"}
{"version":3,"file":"resolveImageUrl.js","sourceRoot":"","sources":["../../src/utils/resolveImageUrl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,IAAI,MAAM,iBAAiB,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEpF,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAI,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC5C;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACrC,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAc,EACd,aAAsB;IAEtB,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;IAED,MAAM,YAAY,GAAG,aAAa,CAChC,aAAa,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAC/C,CAAC;IAEF,IAAI,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE;QACnE,MAAM,OAAO,GAAG,GAAG,IAAI,CAAC,mBAAmB,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,YAAY,EAAE,CAAC;QAChF,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC;YAC7C,OAAO,EAAE,OAAO;YAChB,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC,OAAO,CAAC;QACX,IAAI,UAAU,KAAK,GAAG,EAAE;YACtB,MAAM,IAAI,KAAK,CAAC,0BAA0B,OAAO,EAAE,CAAC,CAAC;SACtD;QACD,IAAI;YACF,OAAO,MAAM,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;SACnD;gBAAS;YACR,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE;gBAC9B,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;aAC5B;SACF;KACF;IAED,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE;QAC1D,OAAO,UAAU,CAAC;KACnB;IAED,IAAI,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;QACpC,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,IAAI,QAAQ,CAAC,EAAE,KAAK,KAAK,IAAI,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QACvD,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE;QACjC,OAAO,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;KAChD;IAED,kEAAkE;IAClE,8DAA8D;IAC9D,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS,EAAE;QAC7B,MAAM,SAAS,GAAG,OAAO;aACtB,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC;aAC5B,OAAO,CAAC,6BAA6B,EAAE,EAAE,CAAC,CAAC;QAC9C,IAAI,SAAS,KAAK,OAAO,EAAE;YACzB,MAAM,OAAO,GAAG,GAAG,IAAI,CAAC,mBAAmB,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,YAAY,EAAE,CAAC;YAChF,MAAM,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;YAC9C,IAAI;gBACF,OAAO,MAAM,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;aACnD;oBAAS;gBACR,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE;oBAC9B,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;iBAC5B;aACF;SACF;KACF;IAED,OAAO,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC9C,CAAC"}

727
example/App.tsx Normal file
View File

@ -0,0 +1,727 @@
/**
* MaskSegmentCanvas Demo
*
*
* - `import ... from 'react-native-mask-segment-canvas'` 使 API
* - import ../src
* - PNG Ref 稿
*
* React Native
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
ActivityIndicator,
Alert,
ScrollView,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import MaskSegmentCanvas, {
type BgrColor,
type MaskSegmentCanvasRef,
type MaskSegmentSession,
type MaskSegmentWatchState,
type MaskSemanticColor,
type PaintCallbackPayload,
type PipelinePreset,
type SavePaintResult,
MASK_SEMANTIC_COLORS,
BASEBOARD_SEMANTIC_NAME,
DEFAULT_PIPELINE_CONFIG,
DEFAULT_MASK_CONFIG,
DEFAULT_PAINT_CONFIG,
DEFAULT_INTERACTION_CONFIG,
prewarmPngBgrCacheAsync,
resolveAssetPath,
} from 'react-native-mask-segment-canvas';
// ============================================================================
// 测试图片 — 两组示例图,支持切换
// 业务项目接入时替换为你的图片路径file:// 或 http(s)://
// ============================================================================
const TEST_IMAGE_GROUPS: Array<{
label: string;
origin: number;
mask: number;
originCacheName: string;
maskCacheName: string;
}> = [
{
label: '图片组 1',
origin: require('./assets/origin.png'),
mask: require('./assets/mask.png'),
originCacheName: 'example_origin_g1.png',
maskCacheName: 'example_mask_g1.png',
},
{
label: '图片组 2',
origin: require('./assets/origin-1.png'),
mask: require('./assets/mask-1.png'),
originCacheName: 'example_origin_g2.png',
maskCacheName: 'example_mask_g2.png',
},
];
// ============================================================================
// 自定义语义色表示例(健身房场景)
// ============================================================================
const GYM_CUSTOM_COLORS: MaskSemanticColor[] = [
{ name: 'wall', hex: '#4363D8', bgr: { b: 216, g: 99, r: 67 } },
{ name: 'ceiling', hex: '#3CB44B', bgr: { b: 75, g: 180, r: 60 } },
{ name: 'floor', hex: '#E6194B', bgr: { b: 75, g: 25, r: 230 } },
{ name: 'window', hex: '#F58231', bgr: { b: 49, g: 130, r: 245 } },
{ name: 'door', hex: '#911EB4', bgr: { b: 180, g: 30, r: 145 } },
{ name: 'pillar', hex: '#46F0F0', bgr: { b: 240, g: 240, r: 70 } },
];
// ============================================================================
// 预设笔刷色(底部色条之外,业务可通过 ref.setPaintColor 设置)
// ============================================================================
const PAINT_PRESETS: Array<{ label: string; color: BgrColor }> = [
{ label: '象牙白', color: { b: 200, g: 230, r: 245 } },
{ label: '米黄', color: { b: 150, g: 220, r: 245 } },
{ label: '浅灰', color: { b: 180, g: 180, r: 180 } },
{ label: '淡蓝', color: { b: 220, g: 200, r: 170 } },
];
// ============================================================================
// watchState 工具
// ============================================================================
const INTERACTIVE_STATES: MaskSegmentWatchState[] = [
'interactive',
'mask_paths_ready',
];
// ============================================================================
// 主页面
// ============================================================================
function App(): React.JSX.Element {
const canvasRef = useRef<MaskSegmentCanvasRef>(null);
// --------------------------------------------------------------------------
// 状态
// --------------------------------------------------------------------------
const [imagePaths, setImagePaths] = useState<{
origin: string;
mask: string;
} | null>(null);
const [pathsError, setPathsError] = useState('');
const [watchState, setWatchState] = useState<MaskSegmentWatchState | ''>('');
const [watchDetail, setWatchDetail] = useState<Record<string, unknown>>({});
const [errorMessage, setErrorMessage] = useState('');
const [toastMessage, setToastMessage] = useState('');
const [saveResult, setSaveResult] = useState<SavePaintResult | null>(null);
const [sessionDraft] = useState<MaskSegmentSession | null>(null);
// Demo 模式
const [useCustomColors, setUseCustomColors] = useState(false);
const [pipelinePreset, setPipelinePreset] = useState<PipelinePreset>('medium');
const [groupIndex, setGroupIndex] = useState(0);
// --------------------------------------------------------------------------
// 派生状态
// --------------------------------------------------------------------------
const isInteractive = INTERACTIVE_STATES.includes(
watchState as MaskSegmentWatchState,
);
const isOutlineReady = watchState === 'mask_paths_ready';
const isInitLoading =
imagePaths != null &&
watchState !== '' &&
!INTERACTIVE_STATES.includes(watchState as MaskSegmentWatchState) &&
watchState !== 'error';
const semanticColors = useCustomColors ? GYM_CUSTOM_COLORS : MASK_SEMANTIC_COLORS;
// --------------------------------------------------------------------------
// 初始化解析测试图路径require → 本地 PNG 缓存路径)
// --------------------------------------------------------------------------
useEffect(() => {
let cancelled = false;
void (async () => {
try {
setWatchState('');
setWatchDetail({});
setErrorMessage('');
setSaveResult(null);
setPathsError('');
setImagePaths(null);
const group = TEST_IMAGE_GROUPS[groupIndex];
const [origin, mask] = await Promise.all([
resolveAssetPath(group.origin, group.originCacheName),
resolveAssetPath(group.mask, group.maskCacheName),
]);
await prewarmPngBgrCacheAsync([origin, mask]);
if (!cancelled) {
setImagePaths({ origin, mask });
}
} catch (e) {
if (!cancelled) {
setPathsError(e instanceof Error ? e.message : String(e));
}
}
})();
return () => {
cancelled = true;
};
}, [groupIndex]);
// --------------------------------------------------------------------------
// Toast 提示
// --------------------------------------------------------------------------
const showToast = useCallback((msg: string) => {
setToastMessage(msg);
setTimeout(() => setToastMessage(''), 2500);
}, []);
// --------------------------------------------------------------------------
// onWatch 回调
// --------------------------------------------------------------------------
const handleWatch = useCallback(
(
state: MaskSegmentWatchState,
durationMs: number,
detail?: Record<string, unknown>,
) => {
setWatchState(state);
if (detail) setWatchDetail(detail);
console.log(
`[Example onWatch] ${state} ${durationMs.toFixed(0)}ms`,
detail ?? '',
);
},
[],
);
// --------------------------------------------------------------------------
// onPaintCallback — 处理上色成功 / 未选笔刷两种场景
// --------------------------------------------------------------------------
const handlePaintCallback = useCallback((payload: PaintCallbackPayload) => {
if (payload.kind === 'brush_required') {
// 用户未选笔刷时点击了分区,业务侧弹提示引导选色
showToast(payload.hint);
console.log('[Example] 需选笔刷:', payload.regionName);
return;
}
// 上色成功
console.log(
'[Example] 上色成功:',
payload.regionName,
`(${payload.regionId})`,
payload.color,
);
}, [showToast]);
// --------------------------------------------------------------------------
// onError 回调
// --------------------------------------------------------------------------
const handleError = useCallback((message: string) => {
setErrorMessage(message);
setWatchState('error');
}, []);
// --------------------------------------------------------------------------
// Ref 操作封装
// --------------------------------------------------------------------------
const handleSave = useCallback(async () => {
if (!isInteractive) return;
try {
const result = await canvasRef.current?.save();
if (result) {
setSaveResult(result);
Alert.alert('保存成功', `路径: ${result.filePath}\n已上色 ${result.paintedCount} 个区域`);
}
} catch (e) {
Alert.alert('保存失败', e instanceof Error ? e.message : String(e));
}
}, [isInteractive]);
const handleReset = useCallback(() => canvasRef.current?.reset(), []);
const handleSwap = useCallback(() => canvasRef.current?.swap(), []);
const handleClearAll = useCallback(() => {
canvasRef.current?.clearAllPaint();
showToast('已清空全部上色');
}, [showToast]);
const handleExportSession = useCallback(() => {
const session = canvasRef.current?.session();
if (session) {
console.log('[Example] 会话快照:', JSON.stringify(session, null, 2));
Alert.alert(
'会话快照',
`已上色 ${session.painted.length} 个区域\n可存入 MMKV / AsyncStorage 实现草稿恢复`,
);
}
}, []);
const handleSetPaintColor = useCallback(
(color: BgrColor, label: string) => {
canvasRef.current?.setPaintColor(color, { preset: label });
showToast(`已选择笔刷: ${label}`);
},
[showToast],
);
// --------------------------------------------------------------------------
// 渲染:错误 / 加载 / 就绪
// --------------------------------------------------------------------------
if (pathsError) {
return (
<SafeAreaView style={styles.root}>
<View style={styles.center}>
<Text style={styles.errorText}></Text>
<Text style={styles.errorDetail}>{pathsError}</Text>
</View>
</SafeAreaView>
);
}
if (!imagePaths) {
return (
<SafeAreaView style={styles.root}>
<View style={styles.center}>
<ActivityIndicator size="large" color="#4363D8" />
<Text style={styles.loadingText}> PNG </Text>
</View>
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.root}>
<StatusBar barStyle="dark-content" backgroundColor="#fff" />
{/* 顶部:状态 + 模式切换 */}
<View style={styles.topBar}>
<View style={styles.topBarRow}>
<Text style={styles.statusLabel}>
:{' '}
<Text
style={[
styles.statusValue,
isInteractive && styles.statusReady,
watchState === 'error' && styles.statusError,
]}
>
{watchState || '初始化…'}
</Text>
{isOutlineReady ? ' · 轮播就绪' : ''}
{isInteractive && !isOutlineReady ? ' · 轮廓加载中' : ''}
</Text>
<Text style={styles.regionCount}>
{watchDetail.regionCount != null
? `${watchDetail.regionCount} 个分区`
: ''}
</Text>
</View>
{/* 模式切换 */}
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={styles.modeRow}
contentContainerStyle={styles.modeRowContent}
>
<TouchableOpacity
style={[styles.modeChip, !useCustomColors && styles.modeChipActive]}
onPress={() => setUseCustomColors(false)}
>
<Text style={[styles.modeChipText, !useCustomColors && styles.modeChipTextActive]}>
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.modeChip, useCustomColors && styles.modeChipActive]}
onPress={() => setUseCustomColors(true)}
>
<Text style={[styles.modeChipText, useCustomColors && styles.modeChipTextActive]}>
</Text>
</TouchableOpacity>
<Text style={styles.modeDivider}>|</Text>
{TEST_IMAGE_GROUPS.map((group, idx) => (
<TouchableOpacity
key={group.label}
style={[styles.modeChip, groupIndex === idx && styles.modeChipActive]}
onPress={() => setGroupIndex(idx)}
>
<Text style={[styles.modeChipText, groupIndex === idx && styles.modeChipTextActive]}>
{group.label}
</Text>
</TouchableOpacity>
))}
<Text style={styles.modeDivider}>|</Text>
{(['low', 'medium', 'high'] as PipelinePreset[]).map(p => (
<TouchableOpacity
key={p}
style={[styles.modeChip, pipelinePreset === p && styles.modeChipActive]}
onPress={() => setPipelinePreset(p)}
>
<Text style={[styles.modeChipText, pipelinePreset === p && styles.modeChipTextActive]}>
{p === 'low' ? '低精度' : p === 'medium' ? '中精度' : '高精度'}
</Text>
</TouchableOpacity>
))}
</ScrollView>
</View>
{/* 画布 */}
<View style={styles.canvasHost}>
<MaskSegmentCanvas
key={`image-group-${groupIndex}`}
ref={canvasRef}
style={styles.canvas}
originUrl={imagePaths.origin}
maskUrl={imagePaths.mask}
semanticColors={semanticColors}
regionOutlineColor="rgba(20, 120, 235, 0.58)"
pipelinePreset={pipelinePreset}
maskConfig={{
...DEFAULT_MASK_CONFIG,
maxRegionColors: 6,
}}
paintConfig={{
...DEFAULT_PAINT_CONFIG,
colorBaseOpacity: 0.88,
}}
interactionConfig={{
...DEFAULT_INTERACTION_CONFIG,
initRegionFlashMs: 1000,
enableInitRegionFlash: true,
}}
showDebugPickers={false}
showToolbar={false}
showColorBar
showStatusRow={false}
showOverlayButtons
disabled={!isInteractive}
initialSession={sessionDraft ?? undefined}
undoButtonText="撤销"
compareButtonText="对比原图"
compareExitButtonText="退出对比"
onWatch={handleWatch}
onPaintCallback={handlePaintCallback}
onError={handleError}
/>
{/* 初始化加载遮罩 */}
{isInitLoading && (
<View style={styles.initOverlay} pointerEvents="none">
<ActivityIndicator size="small" color="#4363D8" />
<Text style={styles.initOverlayText}>
{watchState}
</Text>
</View>
)}
</View>
{/* Toast */}
{toastMessage ? (
<View style={styles.toast} pointerEvents="none">
<Text style={styles.toastText}>{toastMessage}</Text>
</View>
) : null}
{/* 底部:业务操作栏 / Ref 方法演示 */}
<View style={styles.bottomBar}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.bottomBarContent}
>
{/* 预设笔刷(替代底部色条) */}
<Text style={styles.sectionLabel}>:</Text>
{PAINT_PRESETS.map(p => (
<TouchableOpacity
key={p.label}
style={[styles.paintBtn, { backgroundColor: `rgb(${p.color.r},${p.color.g},${p.color.b})` }]}
onPress={() => handleSetPaintColor(p.color, p.label)}
disabled={!isInteractive}
>
<Text style={styles.paintBtnText}>{p.label}</Text>
</TouchableOpacity>
))}
<View style={styles.divider} />
{/* Ref 操作 */}
<Text style={styles.sectionLabel}>:</Text>
<TouchableOpacity
style={[styles.actionBtn, styles.actionBtnDanger]}
onPress={handleReset}
disabled={!isInteractive}
>
<Text style={styles.actionBtnText}></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.actionBtn}
onPress={handleSwap}
disabled={!isInteractive}
>
<Text style={styles.actionBtnText}></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.actionBtn}
onPress={handleClearAll}
disabled={!isInteractive}
>
<Text style={styles.actionBtnText}></Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.actionBtn, styles.actionBtnPrimary]}
onPress={handleSave}
disabled={!isInteractive}
>
<Text style={styles.actionBtnTextPrimary}></Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.actionBtn}
onPress={handleExportSession}
disabled={!isInteractive}
>
<Text style={styles.actionBtnText}></Text>
</TouchableOpacity>
</ScrollView>
</View>
{/* 错误展示 */}
{errorMessage ? (
<View style={styles.errorBar}>
<Text style={styles.errorBarText}>: {errorMessage}</Text>
</View>
) : null}
</SafeAreaView>
);
}
// ============================================================================
// 样式
// ============================================================================
const styles = StyleSheet.create({
root: {
flex: 1,
backgroundColor: '#fff',
},
center: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 24,
},
loadingText: {
marginTop: 12,
color: '#888',
fontSize: 14,
},
errorText: {
color: '#c33',
fontSize: 18,
fontWeight: '600',
},
errorDetail: {
marginTop: 8,
color: '#999',
fontSize: 13,
textAlign: 'center',
},
// 顶部状态栏
topBar: {
paddingHorizontal: 12,
paddingTop: 8,
paddingBottom: 4,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#e8e8e8',
backgroundColor: '#fafafa',
},
topBarRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
statusLabel: {
fontSize: 12,
color: '#888',
},
statusValue: {
fontWeight: '600',
color: '#555',
},
statusReady: {
color: '#2a7',
},
statusError: {
color: '#c33',
},
regionCount: {
fontSize: 11,
color: '#aaa',
},
modeRow: {
marginTop: 6,
},
modeRowContent: {
alignItems: 'center',
gap: 6,
},
modeChip: {
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 12,
backgroundColor: '#eee',
},
modeChipActive: {
backgroundColor: '#4363D8',
},
modeChipText: {
fontSize: 11,
color: '#666',
},
modeChipTextActive: {
color: '#fff',
fontWeight: '600',
},
modeDivider: {
color: '#ddd',
fontSize: 11,
marginHorizontal: 2,
},
// 画布
canvasHost: {
flex: 1,
position: 'relative',
},
canvas: {
flex: 1,
},
initOverlay: {
...StyleSheet.absoluteFillObject,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(255, 255, 255, 0.8)',
gap: 8,
},
initOverlayText: {
color: '#888',
fontSize: 13,
},
// Toast
toast: {
position: 'absolute',
top: 120,
left: 20,
right: 20,
alignItems: 'center',
zIndex: 999,
},
toastText: {
backgroundColor: 'rgba(0,0,0,0.78)',
color: '#fff',
fontSize: 13,
paddingHorizontal: 16,
paddingVertical: 8,
borderRadius: 8,
overflow: 'hidden',
},
// 底部操作栏
bottomBar: {
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: '#e8e8e8',
backgroundColor: '#fafafa',
paddingVertical: 8,
},
bottomBarContent: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 12,
gap: 8,
},
sectionLabel: {
fontSize: 12,
color: '#999',
fontWeight: '600',
},
divider: {
width: 1,
height: 20,
backgroundColor: '#e0e0e0',
marginHorizontal: 4,
},
// 笔刷按钮
paintBtn: {
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 14,
borderWidth: 1.5,
borderColor: '#ddd',
},
paintBtnText: {
fontSize: 11,
color: '#333',
fontWeight: '600',
textShadowColor: 'rgba(255,255,255,0.6)',
textShadowOffset: { width: 0, height: 1 },
textShadowRadius: 2,
},
// 操作按钮
actionBtn: {
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 6,
backgroundColor: '#f0f0f0',
borderWidth: 1,
borderColor: '#ddd',
},
actionBtnPrimary: {
backgroundColor: '#4363D8',
borderColor: '#4363D8',
},
actionBtnDanger: {
borderColor: '#e88',
},
actionBtnText: {
fontSize: 12,
color: '#555',
fontWeight: '500',
},
actionBtnTextPrimary: {
fontSize: 12,
color: '#fff',
fontWeight: '600',
},
// 错误条
errorBar: {
backgroundColor: '#fff0f0',
paddingHorizontal: 12,
paddingVertical: 6,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: '#fcc',
},
errorBarText: {
fontSize: 12,
color: '#c33',
},
});
export default function Root(): React.JSX.Element {
return (
<SafeAreaProvider>
<App />
</SafeAreaProvider>
);
}

211
example/README.md Normal file
View File

@ -0,0 +1,211 @@
# MaskSegmentCanvas Example
这是一个**完全模拟真实业务项目集成**的 Demo展示如何在你的 React Native 工程中接入 `react-native-mask-segment-canvas`
## 与库本身 Demo 的区别
| 项目 | 引入方式 | 用途 |
| ---- | -------- | ---- |
| 根目录 `App.tsx` | `import ... from './src'`(内部源码) | 库作者自测 |
| **本 example/** | `import ... from 'react-native-mask-segment-canvas'`(公开 API | **业务集成参考** |
本 example 只依赖库的公开 API不触碰 `src/` 内部实现,是你接入时可以直接复制的模板。
## 快速开始
```bash
# 1. 进入 example 目录
cd example
# 2. 安装依赖(自动 link 父目录的库)
npm install
# 3. 应用 postinstall 补丁patch-package 修补 react-native-fast-opencv
# npm install 后自动执行,若未执行请手动:
npx patch-package
# 4. iOS安装原生依赖
cd ios && pod install && cd ..
# 5. 启动 Metro
npm start
# 6. 另开终端运行
npm run ios
# 或
npm run android
```
## 文件说明
```
example/
├── App.tsx # ★ 核心:完整的集成示例页面
├── index.js # RN 入口(注册 gesture-handler + Buffer polyfill
├── app.json # 应用名配置
├── package.json # 独立依赖配置,"react-native-mask-segment-canvas": "file:.."
├── metro.config.js # Metro 配置watchFolders 指向父目录)
├── babel.config.js # Babel 配置(含 reanimated 插件)
├── tsconfig.json # TypeScript 配置
└── README.md # 本文件
```
## App.tsx 覆盖的功能点
`App.tsx` 是一个可直接参考的完整页面,涵盖:
| 功能 | 对应代码位置 |
| ---- | ------------ |
| **PNG 预热** | `useEffect``prewarmPngBgrCacheAsync` |
| **状态管理** | `watchState` / `isInteractive` / `isOutlineReady` 等派生状态 |
| **onWatch 回调** | `handleWatch` — 跟踪初始化阶段 |
| **onPaintCallback** | `handlePaintCallback` — 处理上色成功 / 未选笔刷两种场景 |
| **onError 回调** | `handleError` — 捕获分割/加载失败 |
| **Ref 操作** | `save` / `reset` / `swap` / `clearAllPaint` / `session` |
| **setPaintColor** | 预设笔刷色,通过 `ref.setPaintColor` 设置 |
| **自定义语义色表** | `GYM_CUSTOM_COLORS` 示例 + 模式切换 UI |
| **Pipeline 精度切换** | `pipelinePreset` 低/中/高精度切换 |
| **Toast 提示** | 未选笔刷时 `brush_required` 回调 + 自定义 Toast |
| **加载态/错误态 UI** | PNG 预热加载、初始化 Loading、错误展示 |
| **草稿恢复** | `sessionDraft` 状态 + `initialSession` prop |
## 集成到自己项目
### 方式一npm install推荐生产环境
```bash
npm install react-native-mask-segment-canvas
```
### 方式二:本地联调(开发阶段)
```bash
# 在库目录
npm link
# 在你的项目
npm link react-native-mask-segment-canvas
```
你的 `metro.config.js` 需要添加:
```js
const path = require('path');
module.exports = mergeConfig(getDefaultConfig(__dirname), {
watchFolders: [path.resolve(__dirname, '../MaskSegmentApp')],
resolver: {
nodeModulesPaths: [path.resolve(__dirname, 'node_modules')],
},
});
```
### 方式三file: 依赖(本 example 使用的方式)
```json
{
"dependencies": {
"react-native-mask-segment-canvas": "file:../MaskSegmentApp"
}
}
```
### 必装 peerDependencies
```bash
npm install @shopify/react-native-skia react-native-reanimated react-native-fast-opencv react-native-fs buffer
# 若使用相册选图
npm install react-native-image-picker
# 安全区适配
npm install react-native-safe-area-context
```
### postinstall 配置
你的 `package.json` 需要:
```json
{
"scripts": {
"postinstall": "patch-package"
},
"devDependencies": {
"patch-package": "^8.0.1"
}
}
```
## 常见问题
**`npm install` 后报模块找不到?**
- 确认已执行 `postinstall``npx patch-package`
- 检查 Metro 配置中 `watchFolders` 是否包含库目录
**`pod install` 失败?**
```bash
cd ios
bundle install
bundle exec pod install --repo-update
```
**Android 编译错误?**
```bash
cd android && ./gradlew clean && cd ..
```
**运行时出现「重复模块」类错误(最常见)**
在 monorepo、npm link、`file:..` 场景下,经常会遇到下面这些「类似问题」:
- `SkiaPictureView must be a function (received 'undefined')`
- `createAnimatedNode: Animated node[...] already exists`(含 UIFrameGuarded 变体)
- 其他 Fabric ViewManager / native module 单例冲突
**原因**Metro 同时加载了多份 `@shopify/react-native-skia`、`react-native-reanimated`、`react-native-gesture-handler`、`react-native-fast-opencv`、`react-native-safe-area-context` 等 peer 依赖。
**推荐完整解决方案**(直接复制到你的项目):
1. **index.js 最顶部**(必须在最前面):
```js
import 'react-native-gesture-handler';
import 'react-native-reanimated';
import '@shopify/react-native-skia';
```
2. **metro.config.js**(使用 extraNodeModules + blockList 双保险):
```js
const path = require('path');
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
const yourNodeModules = path.resolve(__dirname, 'node_modules');
const singletons = [
'react', 'react-native',
'react-native-reanimated',
'@shopify/react-native-skia',
'react-native-gesture-handler',
'react-native-fast-opencv',
'react-native-safe-area-context',
'react-native-fs',
'react-native-image-picker',
];
module.exports = mergeConfig(getDefaultConfig(__dirname), {
watchFolders: [path.resolve(__dirname, '../MaskSegmentApp')],
resolver: {
nodeModulesPaths: [yourNodeModules],
extraNodeModules: singletons.reduce((acc, p) => (acc[p] = path.resolve(yourNodeModules, p), acc), {}),
blockList: singletons.map(p => new RegExp(`/MaskSegmentApp/node_modules/${p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}/`)),
},
});
```
> `example/metro.config.js` 已经是按这个标准模板写的,可直接参考。
做完上面两步后,**必须**
- 重启 Metro`npx react-native start --reset-cache`
- 重新安装 app建议先 `cd android && ./gradlew clean` 或 iOS pod 后重跑)
这样能一次性解决所有「同类」重复模块导致的运行时错误。

View File

@ -0,0 +1,119 @@
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '../..'
// root = file("../../")
// The folder where the react-native NPM package is. Default is ../../node_modules/react-native
// reactNativeDir = file("../../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
// codegenDir = file("../../node_modules/@react-native/codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
// cliFile = file("../../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
/* Autolinking */
autolinkLibrariesWithApp()
}
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
android {
ndkVersion rootProject.ext.ndkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace "com.masksegmentcanvasexample"
defaultConfig {
applicationId "com.masksegmentcanvasexample"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}

Binary file not shown.

10
example/android/app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,10 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:usesCleartextTraffic="true"
tools:targetApi="28"
tools:ignore="GoogleAppIndexingWarning"/>
</manifest>

View File

@ -0,0 +1,26 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,22 @@
package com.masksegmentcanvasexample
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "MaskSegmentCanvasExample"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}

View File

@ -0,0 +1,44 @@
package com.masksegmentcanvasexample
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, OpenSourceMergedSoMapping)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
}
}

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"
>
<selector>
<!--
This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
-->
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">MaskSegmentCanvasExample</string>
</resources>

View File

@ -0,0 +1,9 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
</style>
</resources>

View File

@ -0,0 +1,21 @@
buildscript {
ext {
buildToolsVersion = "35.0.0"
minSdkVersion = 24
compileSdkVersion = 35
targetSdkVersion = 35
ndkVersion = "27.1.12297006"
kotlinVersion = "2.0.21"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
}
}
apply plugin: "com.facebook.react.rootproject"

View File

@ -0,0 +1,39 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=true
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
example/android/gradlew vendored Executable file
View File

@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
example/android/gradlew.bat vendored Normal file
View File

@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,6 @@
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
rootProject.name = 'MaskSegmentCanvasExample'
include ':app'
includeBuild('../node_modules/@react-native/gradle-plugin')

4
example/app.json Normal file
View File

@ -0,0 +1,4 @@
{
"name": "MaskSegmentCanvasExample",
"displayName": "MaskSegmentCanvas Example"
}

BIN
example/assets/mask-1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 926 KiB

BIN
example/assets/mask.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 695 KiB

BIN
example/assets/origin-1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 KiB

BIN
example/assets/origin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

4
example/babel.config.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
presets: ['module:@react-native/babel-preset'],
plugins: ['react-native-reanimated/plugin'],
};

36
example/index.js Normal file
View File

@ -0,0 +1,36 @@
/**
* @format
*/
// 【关键 - 必须最顶部】按此顺序提前导入带 JSI/原生注册副作用的库。
// 推荐顺序:
// 1. react-native-gesture-handler
// 2. react-native-reanimated
// 3. @shopify/react-native-skia
//
// 配合 example/metro.config.js 的 extraNodeModules + blockList 使用,
// 能彻底避免 monorepo/file: 场景下的重复模块问题:
// - SkiaPictureView config getter undefined
// - createAnimatedNode: Animated node already exists
// - 其他 Fabric / ViewManager 冲突
import 'react-native-gesture-handler';
import 'react-native-reanimated';
import '@shopify/react-native-skia';
import { Buffer } from 'buffer';
global.Buffer = global.Buffer || Buffer;
import { AppRegistry } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import App from './App';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => RootComponent);
function RootComponent() {
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<App />
</GestureHandlerRootView>
);
}

11
example/ios/.xcode.env Normal file
View File

@ -0,0 +1,11 @@
# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.
# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)

View File

@ -0,0 +1,505 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
0C80B921A6F3F58F76C31292 /* libPods-MaskSegmentCanvasExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-MaskSegmentCanvasExample.a */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 13B07F861A680F5B00A75B9A;
remoteInfo = MaskSegmentCanvasExample;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
13B07F961A680F5B00A75B9A /* MaskSegmentCanvasExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MaskSegmentCanvasExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = MaskSegmentCanvasExample/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = MaskSegmentCanvasExample/Info.plist; sourceTree = "<group>"; };
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = MaskSegmentCanvasExample/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
3B4392A12AC88292D35C810B /* Pods-MaskSegmentCanvasExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MaskSegmentCanvasExample.debug.xcconfig"; path = "Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample.debug.xcconfig"; sourceTree = "<group>"; };
5709B34CF0A7D63546082F79 /* Pods-MaskSegmentCanvasExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MaskSegmentCanvasExample.release.xcconfig"; path = "Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample.release.xcconfig"; sourceTree = "<group>"; };
5DCACB8F33CDC322A6C60F78 /* libPods-MaskSegmentCanvasExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MaskSegmentCanvasExample.a"; sourceTree = BUILT_PRODUCTS_DIR; };
761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = MaskSegmentCanvasExample/AppDelegate.swift; sourceTree = "<group>"; };
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = MaskSegmentCanvasExample/LaunchScreen.storyboard; sourceTree = "<group>"; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
0C80B921A6F3F58F76C31292 /* libPods-MaskSegmentCanvasExample.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
00E356F01AD99517003FC87E /* Supporting Files */ = {
isa = PBXGroup;
children = (
00E356F11AD99517003FC87E /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
13B07FAE1A68108700A75B9A /* MaskSegmentCanvasExample */ = {
isa = PBXGroup;
children = (
13B07FB51A68108700A75B9A /* Images.xcassets */,
761780EC2CA45674006654EE /* AppDelegate.swift */,
13B07FB61A68108700A75B9A /* Info.plist */,
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
);
name = MaskSegmentCanvasExample;
sourceTree = "<group>";
};
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
isa = PBXGroup;
children = (
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
5DCACB8F33CDC322A6C60F78 /* libPods-MaskSegmentCanvasExample.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
);
name = Libraries;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* MaskSegmentCanvasExample */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
83CBBA001A601CBA00E9B192 /* Products */,
2D16E6871FA4F8E400B85C8A /* Frameworks */,
BBD78D7AC51CEA395F1C20DB /* Pods */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
usesTabs = 0;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* MaskSegmentCanvasExample.app */,
);
name = Products;
sourceTree = "<group>";
};
BBD78D7AC51CEA395F1C20DB /* Pods */ = {
isa = PBXGroup;
children = (
3B4392A12AC88292D35C810B /* Pods-MaskSegmentCanvasExample.debug.xcconfig */,
5709B34CF0A7D63546082F79 /* Pods-MaskSegmentCanvasExample.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
13B07F861A680F5B00A75B9A /* MaskSegmentCanvasExample */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MaskSegmentCanvasExample" */;
buildPhases = (
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = MaskSegmentCanvasExample;
productName = MaskSegmentCanvasExample;
productReference = 13B07F961A680F5B00A75B9A /* MaskSegmentCanvasExample.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1210;
TargetAttributes = {
13B07F861A680F5B00A75B9A = {
LastSwiftMigration = 1120;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MaskSegmentCanvasExample" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* MaskSegmentCanvasExample */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
00E356EC1AD99517003FC87E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/.xcode.env.local",
"$(SRCROOT)/.xcode.env",
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n";
};
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-MaskSegmentCanvasExample-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MaskSegmentCanvasExample/Pods-MaskSegmentCanvasExample-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
00E356F51AD99517003FC87E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 13B07F861A680F5B00A75B9A /* MaskSegmentCanvasExample */;
targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-MaskSegmentCanvasExample.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = MaskSegmentCanvasExample/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = MaskSegmentCanvasExample;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-MaskSegmentCanvasExample.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = MaskSegmentCanvasExample/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = MaskSegmentCanvasExample;
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MaskSegmentCanvasExample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MaskSegmentCanvasExample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}

View File

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1210"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "MaskSegmentCanvasExample.app"
BlueprintName = "MaskSegmentCanvasExample"
ReferencedContainer = "container:MaskSegmentCanvasExample.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "MaskSegmentCanvasExampleTests.xctest"
BlueprintName = "MaskSegmentCanvasExampleTests"
ReferencedContainer = "container:MaskSegmentCanvasExample.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "MaskSegmentCanvasExample.app"
BlueprintName = "MaskSegmentCanvasExample"
ReferencedContainer = "container:MaskSegmentCanvasExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "MaskSegmentCanvasExample.app"
BlueprintName = "MaskSegmentCanvasExample"
ReferencedContainer = "container:MaskSegmentCanvasExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,48 @@
import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reactNativeDelegate: ReactNativeDelegate?
var reactNativeFactory: RCTReactNativeFactory?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
let factory = RCTReactNativeFactory(delegate: delegate)
delegate.dependencyProvider = RCTAppDependencyProvider()
reactNativeDelegate = delegate
reactNativeFactory = factory
window = UIWindow(frame: UIScreen.main.bounds)
factory.startReactNative(
withModuleName: "MaskSegmentCanvasExample",
in: window,
launchOptions: launchOptions
)
return true
}
}
class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {
override func sourceURL(for bridge: RCTBridge) -> URL? {
self.bundleURL()
}
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
}

View File

@ -0,0 +1,53 @@
{
"images" : [
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>MaskSegmentCanvas Example</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<!-- Do not change NSAllowsArbitraryLoads to true, or you will risk app rejection! -->
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15704"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="MaskSegmentCanvasExample" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="202" width="375" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Powered by React Native" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
<rect key="frame" x="0.0" y="626" width="375" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="bottom" secondItem="MN2-I3-ftu" secondAttribute="bottom" constant="20" id="OZV-Vh-mqD"/>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="centerX" secondItem="Bcu-3y-fUS" secondAttribute="centerX" id="akx-eg-2ui"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" id="i1E-0Y-4RG"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/3" constant="1" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" symbolic="YES" id="x7j-FC-K8j"/>
</constraints>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="52.173913043478265" y="375"/>
</scene>
</scenes>
</document>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>C617.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
</dict>
</array>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTracking</key>
<false/>
</dict>
</plist>

35
example/ios/Podfile Normal file
View File

@ -0,0 +1,35 @@
# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
'require.resolve(
"react-native/scripts/react_native_pods.rb",
{paths: [process.argv[1]]},
)', __dir__]).strip
platform :ios, min_ios_version_supported
prepare_react_native_project!
linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
use_frameworks! :linkage => linkage.to_sym
end
target 'MaskSegmentCanvasExample' do
config = use_native_modules!
use_react_native!(
:path => config[:reactNativePath],
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
post_install do |installer|
# https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
react_native_post_install(
installer,
config[:reactNativePath],
:mac_catalyst_enabled => false,
# :ccache_enabled => true
)
end
end

55
example/metro.config.js Normal file
View File

@ -0,0 +1,55 @@
const path = require('path');
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
/**
* Metro configuration for the example app.
*
* 关键目标 monorepo / "file:.." / npm link 场景下保证所有带原生/JSI/Fabric 代码的
* peer 依赖都只解析到 **example/node_modules** 下的那一份
*
* 重复解析会导致各种类似问题
* - SkiaPictureView config getter undefined
* - createAnimatedNode: Animated node[...] already exists (Reanimated)
* - 各种 View 注册冲突Invalid hook call
*
* 维护原则凡是 package.json peerDependencies 里声明的且包含原生代码的都必须在这里强制单例
*/
const parentRoot = path.resolve(__dirname, '..');
const exampleNodeModules = path.resolve(__dirname, 'node_modules');
// 必须单例的依赖列表(来自本库的 peerDependencies + 常见会引发冲突的)。
// 以后新增 peer 依赖时,记得同步更新这里。
const singletonPackages = [
'react',
'react-native',
'react-native-reanimated',
'@shopify/react-native-skia',
'react-native-gesture-handler',
'react-native-fast-opencv',
'react-native-safe-area-context',
'react-native-fs',
// 可选 peer
'react-native-image-picker',
];
const config = {
watchFolders: [parentRoot],
resolver: {
nodeModulesPaths: [exampleNodeModules],
// 方式一最强extraNodeModules 强制别名
// 让 import 'xxx' 永远拿到 example/node_modules 里的实例
extraNodeModules: singletonPackages.reduce((acc, pkg) => {
acc[pkg] = path.resolve(exampleNodeModules, pkg);
return acc;
}, {}),
// 方式二双保险blockList 完全禁止 Metro 去父目录的 node_modules 里找这些包
blockList: singletonPackages.map(
(pkg) => new RegExp(`/MaskSegmentApp/node_modules/${pkg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/`),
),
},
};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);

6480
example/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

36
example/package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "mask-segment-canvas-example",
"version": "0.1.0",
"private": true,
"scripts": {
"postinstall": "patch-package",
"start": "react-native start",
"ios": "react-native run-ios",
"android": "react-native run-android",
"pod:install": "cd ios && pod install"
},
"dependencies": {
"react": "19.0.0",
"react-native": "0.79.4",
"react-native-mask-segment-canvas": "file:..",
"@shopify/react-native-skia": "^2.6.4",
"react-native-fast-opencv": "^0.4.8",
"react-native-fs": "^2.20.0",
"react-native-gesture-handler": "^2.16.0",
"react-native-image-picker": "^8.2.1",
"react-native-reanimated": "^3.19.5",
"react-native-safe-area-context": "^5.8.0",
"buffer": "^6.0.3"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.3",
"@babel/runtime": "^7.25.0",
"@react-native/babel-preset": "0.79.4",
"@react-native/metro-config": "0.79.4",
"@react-native/typescript-config": "0.79.4",
"@types/react": "^19.0.0",
"patch-package": "^8.0.1",
"typescript": "5.0.4"
}
}

1
example/patches Symbolic link
View File

@ -0,0 +1 @@
../patches

3
example/tsconfig.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "@react-native/typescript-config/tsconfig.json"
}

View File

@ -2,7 +2,15 @@
* @format
*/
// 【关键】在入口最顶部、任何其他代码之前按顺序导入这些包。
// 顺序推荐gesture-handler → reanimated → skia
// 目的:确保 JSI / Fabric 组件的 install 和注册只在“正确单例”上执行一次。
// 缺失或顺序错误 + 重复模块解析 → 各种类似错误:
// SkiaPictureView must be a function (undefined)
// createAnimatedNode: Animated node already exists
import 'react-native-gesture-handler';
import 'react-native-reanimated';
import '@shopify/react-native-skia';
import { Buffer } from 'buffer';

View File

@ -1,11 +1,47 @@
const path = require('path');
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
/**
* Metro configuration
* https://reactnative.dev/docs/metro
* Metro configuration for library development (root).
*
* @type {import('@react-native/metro-config').MetroConfig}
* 主要目的
* - 当同时存在 example/ 目录时防止 Metro 意外从 example/node_modules 里解析到
* 另一份 react / reanimated / skia 等带原生/JSI 的包导致和根目录的实例冲突
*
* 如果你只在 example/ 目录下开发测试请优先关注 example/metro.config.js
*
* 这里也使用和 example 一致的 singletonPackages 列表方便维护
*/
const config = {};
const rootNodeModules = path.resolve(__dirname, 'node_modules');
const exampleNodeModules = path.resolve(__dirname, 'example/node_modules');
// 与 example/ 保持一致的必须单例列表
const singletonPackages = [
'react',
'react-native',
'react-native-reanimated',
'@shopify/react-native-skia',
'react-native-gesture-handler',
'react-native-fast-opencv',
'react-native-safe-area-context',
'react-native-fs',
'react-native-image-picker',
];
const config = {
resolver: {
nodeModulesPaths: [rootNodeModules, exampleNodeModules],
extraNodeModules: singletonPackages.reduce((acc, pkg) => {
acc[pkg] = path.resolve(rootNodeModules, pkg);
return acc;
}, {}),
blockList: singletonPackages.map(
(pkg) => new RegExp(`/example/node_modules/${pkg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/`),
),
},
};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);

View File

@ -1,6 +1,6 @@
{
{
"name": "react-native-mask-segment-canvas",
"version": "0.1.0",
"version": "0.2.0",
"description": "React Native 掩码分区交互库OpenCV 语义分割 + SkSL Shader 上色",
"main": "dist/index.js",
"module": "dist/index.js",

9
react-native.config.js Normal file
View File

@ -0,0 +1,9 @@
// react-native-mask-segment-canvas is a pure JS library — no native modules to link.
module.exports = {
dependency: {
platforms: {
android: null,
ios: null,
},
},
};

View File

@ -36,7 +36,7 @@ import {
prewarmPngBgrCache,
resizeBgrBuffer,
} from '../utils/pngImage';
import { resolveImageUrl } from '../utils/resolveImageUrl';
import { hashUrl, resolveImageUrl } from '../utils/resolveImageUrl';
import { compositePaintedImage } from '../utils/compositePaintedImage';
import {
paintedRegionsFingerprint,
@ -713,8 +713,8 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
void (async () => {
try {
const [originPath, maskPath] = await Promise.all([
resolveImageUrl(originSource, 'origin.png'),
resolveImageUrl(maskSource, 'mask.png'),
resolveImageUrl(originSource, `origin_${hashUrl(originSource)}.png`),
resolveImageUrl(maskSource, `mask_${hashUrl(maskSource)}.png`),
]);
if (!cancelled) {
setResolvedOriginPath(originPath);
@ -1315,7 +1315,10 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
);
const loadPaintLayersIfNeeded = useCallback(() => {
if (paintResourcesReady) {
// Use the ref (synced in segmentAndPrepareLayers cleanup) rather than
// paintResourcesReady state — after switching origin/mask URLs the state
// may still read true for one frame while layers were already released.
if (paintResourceLayersRef.current) {
return Promise.resolve();
}
if (paintLayersPromiseRef.current) {
@ -1382,7 +1385,7 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
})();
paintLayersPromiseRef.current = promise;
return promise;
}, [emitInteractiveIfReady, paintResourcesReady]);
}, [emitInteractiveIfReady]);
loadPaintLayersRef.current = loadPaintLayersIfNeeded;
@ -1897,8 +1900,12 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
// Stable refs for functions called inside gesture closures
const findRegionAtPointRef = useRef(findRegionAtPoint);
const onCanvasTapRef = useRef(onCanvasTap);
const onUserInteractionRef = useRef(onUserInteraction);
const resetZoomRef = useRef(resetZoom);
useEffect(() => { findRegionAtPointRef.current = findRegionAtPoint; }, [findRegionAtPoint]);
useEffect(() => { onCanvasTapRef.current = onCanvasTap; }, [onCanvasTap]);
useEffect(() => { onUserInteractionRef.current = onUserInteraction; }, [onUserInteraction]);
useEffect(() => { resetZoomRef.current = resetZoom; }, [resetZoom]);
const undoSelection = useCallback(() => {
onUserInteraction();
@ -2364,7 +2371,7 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
// Immediate hold highlight — fires on touch-down regardless of brush state.
// When a brush is active, this lets the user preview which region they're
// about to paint before lifting their finger.
onUserInteraction();
onUserInteractionRef.current?.();
const coords = screenToCanvasCoords(
x, y,
canvasWRef.current, canvasHRef.current,
@ -2446,7 +2453,7 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
runOnJS(onFinalizeJS)(e.x, e.y);
});
},
[onUserInteraction],
[], // 仅创建一次手势对象;所有回调都通过 Ref 读取最新值,避免初始化期间重复创建导致 Reanimated 节点冲突
);
// ── Gesture: pinch-zoom (two-finger scale; max 5×) ─────────────────────
@ -2467,7 +2474,7 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
};
const onEndJS = () => {
if (zoomScaleRef.current <= 1.01) {
resetZoom();
resetZoomRef.current?.();
}
};
@ -2485,13 +2492,15 @@ const MaskSegmentCanvas = forwardRef<MaskSegmentCanvasRef, MaskSegmentCanvasProp
runOnJS(onEndJS)();
});
},
[resetZoom],
[], // 仅创建一次;通过 Ref 访问 resetZoom
);
// ── Composed: Race ensures single-tap and pinch-zoom never conflict ─────────
// 依赖置空 + 内部的 tap/pinch 也用 [],保证整个手势描述符树只在 mount 时创建一次。
// 避免初始化阶段反复创建导致 Reanimated / RNGH 内部节点重复分配。
const composedGesture = useMemo(
() => Gesture.Race(tapGesture, pinchGesture),
[tapGesture, pinchGesture],
[],
);

View File

@ -43,3 +43,4 @@ export {
prewarmPngBgrCache,
prewarmPngBgrCacheAsync,
} from './utils/pngImage';
export { resolveAssetPath } from './utils/resolveAssetPath';

View File

@ -2,7 +2,7 @@ import { Platform } from 'react-native';
import RNFS from 'react-native-fs';
import { ensurePngFile, isPngPath, normalizePath, toPngFileName } from './pngImage';
function hashUrl(url: string): string {
export function hashUrl(url: string): string {
let hash = 0;
for (let i = 0; i < url.length; i++) {
hash = (hash * 31 + url.charCodeAt(i)) | 0;
@ -59,5 +59,24 @@ export async function resolveImageUrl(
return ensurePngFile(normalized, pngCacheName);
}
// Android bundled assets: resolveAssetSource may yield asset:/ or
// file:///android_asset/ URIs that RNFS cannot read directly.
if (Platform.OS === 'android') {
const assetPath = trimmed
.replace(/^asset:\/?\/?/, '')
.replace(/^file:\/\/\/android_asset\//, '');
if (assetPath !== trimmed) {
const tmpDest = `${RNFS.CachesDirectoryPath}/tmp_${Date.now()}_${pngCacheName}`;
await RNFS.copyFileAssets(assetPath, tmpDest);
try {
return await ensurePngFile(tmpDest, pngCacheName);
} finally {
if (await RNFS.exists(tmpDest)) {
await RNFS.unlink(tmpDest);
}
}
}
}
return ensurePngFile(trimmed, pngCacheName);
}