())
83 | {
84 | module.DispatchCommand(commandId, commandArgsReader);
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto init
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto init
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :init
68 | @rem Get command-line arguments, handling Windows variants
69 |
70 | if not "%OS%" == "Windows_NT" goto win9xME_args
71 |
72 | :win9xME_args
73 | @rem Slurp the command line arguments.
74 | set CMD_LINE_ARGS=
75 | set _SKIP=2
76 |
77 | :win9xME_args_slurp
78 | if "x%~1" == "x" goto execute
79 |
80 | set CMD_LINE_ARGS=%*
81 |
82 | :execute
83 | @rem Setup the command line
84 |
85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
86 |
87 | @rem Execute Gradle
88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
89 |
90 | :end
91 | @rem End local scope for the variables with windows NT shell
92 | if "%ERRORLEVEL%"=="0" goto mainEnd
93 |
94 | :fail
95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
96 | rem the _cmd.exe /c_ return code!
97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
98 | exit /b 1
99 |
100 | :mainEnd
101 | if "%OS%"=="Windows_NT" endlocal
102 |
103 | :omega
104 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/example/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.example;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceManager;
23 | import com.facebook.react.bridge.ReactContext;
24 | import com.facebook.react.modules.network.NetworkingModule;
25 | import okhttp3.OkHttpClient;
26 |
27 | public class ReactNativeFlipper {
28 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
29 | if (FlipperUtils.shouldEnableFlipper(context)) {
30 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
31 |
32 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
33 | client.addPlugin(new ReactFlipperPlugin());
34 | client.addPlugin(new DatabasesFlipperPlugin(context));
35 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
36 | client.addPlugin(CrashReporterPlugin.getInstance());
37 |
38 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 | NetworkingModule.setCustomClientBuilder(
40 | new NetworkingModule.CustomClientBuilder() {
41 | @Override
42 | public void apply(OkHttpClient.Builder builder) {
43 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 | }
45 | });
46 | client.addPlugin(networkFlipperPlugin);
47 | client.start();
48 |
49 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
50 | // Hence we run if after all native modules have been initialized
51 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
52 | if (reactContext == null) {
53 | reactInstanceManager.addReactInstanceEventListener(
54 | new ReactInstanceManager.ReactInstanceEventListener() {
55 | @Override
56 | public void onReactContextInitialized(ReactContext reactContext) {
57 | reactInstanceManager.removeReactInstanceEventListener(this);
58 | reactContext.runOnNativeModulesQueueThread(
59 | new Runnable() {
60 | @Override
61 | public void run() {
62 | client.addPlugin(new FrescoFlipperPlugin());
63 | }
64 | });
65 | }
66 | });
67 | } else {
68 | client.addPlugin(new FrescoFlipperPlugin());
69 | }
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/example/ios/example.xcodeproj/xcshareddata/xcschemes/example.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/example/ios/example.xcodeproj/xcshareddata/xcschemes/example-tvOS.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/windows/RNSketchCanvas/RNSketchCanvas.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "pch.h"
4 | #include "winrt/Microsoft.ReactNative.h"
5 | #include "NativeModules.h"
6 | #include "RNSketchCanvasView.g.h"
7 | #include "SketchData.h"
8 |
9 | namespace winrt::RNSketchCanvas::implementation
10 | {
11 | class RNSketchCanvasView : public RNSketchCanvasViewT
12 | {
13 | public:
14 | RNSketchCanvasView(Microsoft::ReactNative::IReactContext const& reactContext);
15 |
16 | void openImageFile(std::string filename, std::string directory, std::string mode);
17 |
18 | static winrt::Windows::Foundation::Collections::
19 | IMapView
20 | NativeProps() noexcept;
21 | void UpdateProperties(winrt::Microsoft::ReactNative::IJSValueReader const& propertyMapReader) noexcept;
22 |
23 |
24 | static winrt::Microsoft::ReactNative::ConstantProviderDelegate
25 | ExportedViewConstants() noexcept;
26 |
27 | static winrt::Microsoft::ReactNative::ConstantProviderDelegate
28 | ExportedCustomBubblingEventTypeConstants() noexcept;
29 | static winrt::Microsoft::ReactNative::ConstantProviderDelegate
30 | ExportedCustomDirectEventTypeConstants() noexcept;
31 |
32 | static winrt::Windows::Foundation::Collections::IVectorView Commands() noexcept;
33 | void DispatchCommand(
34 | winrt::hstring const& commandId,
35 | winrt::Microsoft::ReactNative::IJSValueReader const& commandArgsReader) noexcept;
36 |
37 | void clear();
38 | void newPath(int32_t id, uint32_t strokeColor, float strokeWidth);
39 | void addPoint(float x, float y);
40 | void addPath(int32_t id, uint32_t strokeColor, float strokeWidth, std::vector points);
41 | void deletePath(int32_t id);
42 | void end();
43 | void save(std::string format, std::string folder, std::string filename, bool transparent, bool includeImage, bool cropToImageSize);
44 |
45 | IAsyncOperation getBase64(std::string format, bool transparent, bool includeImage, bool cropToImageSize);
46 |
47 | private:
48 | std::vector> mPaths;
49 | std::shared_ptr mCurrentPath = nullptr;
50 |
51 | Microsoft::Graphics::Canvas::UI::Xaml::CanvasControl mCanvasControl;
52 |
53 | bool mNeedsFullRedraw = true;
54 | std::optional mDrawingCanvas = std::nullopt;
55 | std::optional mTranslucentDrawingCanvas = std::nullopt;
56 |
57 | std::optional mBackgroundImage;
58 | int mOriginalWidth, mOriginalHeight;
59 | std::string mContentMode;
60 |
61 | IAsyncOperation saveHelper(std::string format, std::string folder, std::string filename, bool transparent, bool includeImage, bool cropToImageSize);
62 |
63 | Microsoft::ReactNative::IReactContext m_reactContext{ nullptr };
64 | void OnCanvasDraw(Microsoft::Graphics::Canvas::UI::Xaml::CanvasControl const&, Microsoft::Graphics::Canvas::UI::Xaml::CanvasDrawEventArgs const&);
65 | void OnCanvasSizeChanged(const winrt::Windows::Foundation::IInspectable, Windows::UI::Xaml::SizeChangedEventArgs const&);
66 | Microsoft::Graphics::Canvas::UI::Xaml::CanvasControl::Draw_revoker mCanvasDrawRevoker{};
67 | Microsoft::Graphics::Canvas::UI::Xaml::CanvasControl::SizeChanged_revoker mCanvaSizeChangedRevoker{};
68 |
69 | void onSaved(bool success, std::string path);
70 |
71 | void invalidateCanvas(bool shouldDispatchEvent);
72 | Microsoft::Graphics::Canvas::CanvasBitmap createImage(bool transparent, bool includeImage, bool cropToImageSize);
73 | };
74 | }
75 |
76 | namespace winrt::RNSketchCanvas::factory_implementation
77 | {
78 | struct RNSketchCanvasView : RNSketchCanvasViewT {};
79 | }
80 |
--------------------------------------------------------------------------------
/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchCanvasManager.java:
--------------------------------------------------------------------------------
1 | package com.terrylinla.rnsketchcanvas;
2 |
3 | import android.app.Activity;
4 | import android.content.BroadcastReceiver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.IntentFilter;
8 | import android.content.pm.ActivityInfo;
9 | import android.content.res.Configuration;
10 | import android.util.Log;
11 |
12 | import com.facebook.common.logging.FLog;
13 | import com.facebook.react.bridge.Callback;
14 | import com.facebook.react.bridge.ReadableArray;
15 | import com.facebook.react.bridge.ReadableMap;
16 | import com.facebook.react.bridge.ReactMethod;
17 | import com.facebook.react.common.ReactConstants;
18 | import com.facebook.react.common.MapBuilder;
19 | import com.facebook.react.modules.core.DeviceEventManagerModule;
20 | import com.facebook.react.uimanager.SimpleViewManager;
21 | import com.facebook.react.uimanager.ThemedReactContext;
22 | import com.facebook.react.uimanager.annotations.ReactProp;
23 |
24 | import java.util.HashMap;
25 | import java.util.Map;
26 | import java.util.ArrayList;
27 | import android.graphics.PointF;
28 |
29 | import javax.annotation.Nullable;
30 |
31 | public class SketchCanvasManager extends SimpleViewManager {
32 | public static final int COMMAND_ADD_POINT = 1;
33 | public static final int COMMAND_NEW_PATH = 2;
34 | public static final int COMMAND_CLEAR = 3;
35 | public static final int COMMAND_ADD_PATH = 4;
36 | public static final int COMMAND_DELETE_PATH = 5;
37 | public static final int COMMAND_SAVE = 6;
38 | public static final int COMMAND_END_PATH = 7;
39 |
40 | public static SketchCanvas Canvas = null;
41 |
42 | private static final String PROPS_LOCAL_SOURCE_IMAGE = "localSourceImage";
43 |
44 | @Override
45 | public String getName() {
46 | return "RNSketchCanvas";
47 | }
48 |
49 | @Override
50 | protected SketchCanvas createViewInstance(ThemedReactContext context) {
51 | SketchCanvasManager.Canvas = new SketchCanvas(context);
52 | return SketchCanvasManager.Canvas;
53 | }
54 |
55 | @ReactProp(name = PROPS_LOCAL_SOURCE_IMAGE)
56 | public void setLocalSourceImage(SketchCanvas viewContainer, ReadableMap localSourceImage) {
57 | if (localSourceImage != null && localSourceImage.getString("filename") != null) {
58 | viewContainer.openImageFile(
59 | localSourceImage.hasKey("filename") ? localSourceImage.getString("filename") : null,
60 | localSourceImage.hasKey("directory") ? localSourceImage.getString("directory") : "",
61 | localSourceImage.hasKey("mode") ? localSourceImage.getString("mode") : ""
62 | );
63 | }
64 | }
65 |
66 | @Override
67 | public Map getCommandsMap() {
68 | Map map = new HashMap<>();
69 |
70 | map.put("addPoint", COMMAND_ADD_POINT);
71 | map.put("newPath", COMMAND_NEW_PATH);
72 | map.put("clear", COMMAND_CLEAR);
73 | map.put("addPath", COMMAND_ADD_PATH);
74 | map.put("deletePath", COMMAND_DELETE_PATH);
75 | map.put("save", COMMAND_SAVE);
76 | map.put("endPath", COMMAND_END_PATH);
77 |
78 | return map;
79 | }
80 |
81 | @Override
82 | protected void addEventEmitters(ThemedReactContext reactContext, SketchCanvas view) {
83 |
84 | }
85 |
86 | @Override
87 | public void receiveCommand(SketchCanvas view, int commandType, @Nullable ReadableArray args) {
88 | switch (commandType) {
89 | case COMMAND_ADD_POINT: {
90 | view.addPoint((float)args.getDouble(0), (float)args.getDouble(1));
91 | return;
92 | }
93 | case COMMAND_NEW_PATH: {
94 | view.newPath(args.getInt(0), args.getInt(1), (float)args.getDouble(2));
95 | return;
96 | }
97 | case COMMAND_CLEAR: {
98 | view.clear();
99 | return;
100 | }
101 | case COMMAND_ADD_PATH: {
102 | ReadableArray path = args.getArray(3);
103 | ArrayList pointPath = new ArrayList(path.size());
104 | for (int i=0; i
4 | #import
5 | #import
6 | #import
7 |
8 | @implementation RNSketchCanvasManager
9 |
10 | RCT_EXPORT_MODULE()
11 |
12 | + (BOOL)requiresMainQueueSetup
13 | {
14 | return YES;
15 | }
16 |
17 | -(NSDictionary *)constantsToExport {
18 | return @{
19 | @"MainBundlePath": [[NSBundle mainBundle] bundlePath],
20 | @"NSDocumentDirectory": [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject],
21 | @"NSLibraryDirectory": [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject],
22 | @"NSCachesDirectory": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject],
23 | };
24 | }
25 |
26 | #pragma mark - Events
27 |
28 | RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock);
29 |
30 | #pragma mark - Props
31 | RCT_CUSTOM_VIEW_PROPERTY(localSourceImage, NSDictionary, RNSketchCanvas)
32 | {
33 | RNSketchCanvas *currentView = !view ? defaultView : view;
34 | NSDictionary *dict = [RCTConvert NSDictionary:json];
35 | dispatch_async(dispatch_get_main_queue(), ^{
36 | [currentView openSketchFile:dict[@"filename"]
37 | directory:[dict[@"directory"] isEqual: [NSNull null]] ? @"" : dict[@"directory"]
38 | contentMode:[dict[@"mode"] isEqual: [NSNull null]] ? @"" : dict[@"mode"]];
39 | });
40 | }
41 |
42 | #pragma mark - Lifecycle
43 |
44 | - (UIView *)view
45 | {
46 | return [[RNSketchCanvas alloc] initWithEventDispatcher: self.bridge.eventDispatcher];
47 | }
48 |
49 | #pragma mark - Exported methods
50 |
51 |
52 | RCT_EXPORT_METHOD(save:(nonnull NSNumber *)reactTag type:(NSString*) type folder:(NSString*) folder filename:(NSString*) filename withTransparentBackground:(BOOL) transparent includeImage:(BOOL)includeImage cropToImageSize:(BOOL)cropToImageSize)
53 | {
54 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
55 | [canvas saveImageOfType:type folder:folder filename:filename withTransparentBackground:transparent includeImage:includeImage cropToImageSize:cropToImageSize];
56 | }];
57 | }
58 |
59 | RCT_EXPORT_METHOD(addPoint:(nonnull NSNumber *)reactTag x: (float)x y: (float)y)
60 | {
61 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
62 | [canvas addPointX:x Y:y];
63 | }];
64 | }
65 |
66 | RCT_EXPORT_METHOD(addPath:(nonnull NSNumber *)reactTag pathId: (int) pathId strokeColor: (UIColor*) strokeColor strokeWidth: (int) strokeWidth points: (NSArray*) points)
67 | {
68 | NSMutableArray *cgPoints = [[NSMutableArray alloc] initWithCapacity: points.count];
69 | for (NSString *coor in points) {
70 | @autoreleasepool {
71 | NSArray *coorInNumber = [coor componentsSeparatedByString: @","];
72 | [cgPoints addObject: [NSValue valueWithCGPoint: CGPointMake([coorInNumber[0] floatValue], [coorInNumber[1] floatValue])]];
73 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
74 | [canvas addPath: pathId strokeColor: strokeColor strokeWidth: strokeWidth points: cgPoints];
75 | }];
76 | }
77 | }
78 | }
79 |
80 | RCT_EXPORT_METHOD(newPath:(nonnull NSNumber *)reactTag pathId: (int) pathId strokeColor: (UIColor*) strokeColor strokeWidth: (int) strokeWidth)
81 | {
82 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
83 | [canvas newPath: pathId strokeColor: strokeColor strokeWidth: strokeWidth];
84 | }];
85 | }
86 |
87 | RCT_EXPORT_METHOD(deletePath:(nonnull NSNumber *)reactTag pathId: (int) pathId)
88 | {
89 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
90 | [canvas deletePath: pathId];
91 | }];
92 | }
93 |
94 | RCT_EXPORT_METHOD(endPath:(nonnull NSNumber *)reactTag)
95 | {
96 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
97 | [canvas endPath];
98 | }];
99 | }
100 |
101 | RCT_EXPORT_METHOD(clear:(nonnull NSNumber *)reactTag)
102 | {
103 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
104 | [canvas clear];
105 | }];
106 | }
107 |
108 | RCT_EXPORT_METHOD(transferToBase64:(nonnull NSNumber *)reactTag type: (NSString*) type withTransparentBackground:(BOOL) transparent includeImage:(BOOL)includeImage cropToImageSize:(BOOL)cropToImageSize :(RCTResponseSenderBlock)callback)
109 | {
110 | [self runCanvas:reactTag block:^(RNSketchCanvas *canvas) {
111 | callback(@[[NSNull null], [canvas transferToBase64OfType: type withTransparentBackground: transparent includeImage:includeImage cropToImageSize:cropToImageSize]]);
112 | }];
113 | }
114 |
115 | #pragma mark - Utils
116 |
117 | - (void)runCanvas:(nonnull NSNumber *)reactTag block:(void (^)(RNSketchCanvas *canvas))block {
118 | [self.bridge.uiManager addUIBlock:
119 | ^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry){
120 |
121 | RNSketchCanvas *view = viewRegistry[reactTag];
122 | if (!view || ![view isKindOfClass:[RNSketchCanvas class]]) {
123 | RCTLogError(@"Cannot find RNSketchCanvas with tag #%@", reactTag);
124 | return;
125 | }
126 |
127 | block(view);
128 | }];
129 | }
130 |
131 | @end
132 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import { StyleProp, ViewStyle, ViewProps } from "react-native";
3 |
4 | type ImageType = "png" | "jpg";
5 |
6 | type Size = {
7 | width: number;
8 | height: number;
9 | };
10 |
11 | type PathData = {
12 | id: number;
13 | color: string;
14 | width: number;
15 | data: string[];
16 | };
17 |
18 | type Path = {
19 | drawer?: string;
20 | size: Size;
21 | path: PathData;
22 | };
23 |
24 | export interface SavePreference {
25 | folder: string;
26 | filename: string;
27 | transparent: boolean;
28 | imageType: ImageType;
29 | includeImage?: boolean;
30 | cropToImageSize?: boolean;
31 | }
32 |
33 | export interface LocalSourceImage {
34 | path: string;
35 | directory?: string;
36 | mode?: "AspectFill" | "AspectFit" | "ScaleToFill";
37 | }
38 |
39 | export interface SketchCanvasProps {
40 | style?: StyleProp;
41 | strokeColor?: string;
42 | strokeWidth?: number;
43 | user?: string;
44 |
45 | localSourceImage?: LocalSourceImage;
46 | touchEnabled?: boolean;
47 |
48 | /**
49 | * Android Only: Provide a Dialog Title for the Image Saving PermissionDialog. Defaults to empty string if not set
50 | */
51 | permissionDialogTitle?: string;
52 |
53 | /**
54 | * Android Only: Provide a Dialog Message for the Image Saving PermissionDialog. Defaults to empty string if not set
55 | */
56 | permissionDialogMessage?: string;
57 |
58 | onStrokeStart?: () => void;
59 | onStrokeChanged?: () => void;
60 | onStrokeEnd?: (path: Path) => void;
61 | onSketchSaved?: (result: boolean, path: string) => void;
62 | onPathsChange?: (pathsCount: number) => void;
63 | }
64 |
65 | export class SketchCanvas extends React.Component {
66 | clear(): void;
67 | undo(): number;
68 | addPath(data: Path): void;
69 | deletePath(id: number): void;
70 |
71 | /**
72 | * @param imageType "png" or "jpg"
73 | * @param includeImage Set to `true` to include the image loaded from `LocalSourceImage`
74 | * @param cropToImageSize Set to `true` to crop output image to the image loaded from `LocalSourceImage`
75 | */
76 | save(
77 | imageType: ImageType,
78 | transparent: boolean,
79 | folder: string,
80 | filename: string,
81 | includeImage: boolean,
82 | cropToImageSize: boolean
83 | ): void;
84 | getPaths(): Path[];
85 |
86 | /**
87 | * @param imageType "png" or "jpg"
88 | * @param includeImage Set to `true` to include the image loaded from `LocalSourceImage`
89 | * @param cropToImageSize Set to `true` to crop output image to the image loaded from `LocalSourceImage`
90 | */
91 | getBase64(
92 | imageType: ImageType,
93 | transparent: boolean,
94 | includeImage: boolean,
95 | cropToImageSize: boolean,
96 | callback: (error: any, result?: string) => void
97 | ): void;
98 |
99 | static MAIN_BUNDLE: string;
100 | static DOCUMENT: string;
101 | static LIBRARY: string;
102 | static CACHES: string;
103 | static TEMPORARY: string;
104 | static ROAMING: string;
105 | static LOCAL: string;
106 | }
107 |
108 | export interface RNSketchCanvasProps {
109 | containerStyle?: StyleProp;
110 | canvasStyle?: StyleProp;
111 | onStrokeStart?: () => void;
112 | onStrokeChanged?: () => void;
113 | onStrokeEnd?: (path: Path) => void;
114 | onClosePressed?: () => void;
115 | onUndoPressed?: (id: number) => void;
116 | onClearPressed?: () => void;
117 | onPathsChange?: (pathsCount: number) => void;
118 | user?: string;
119 |
120 | closeComponent?: JSX.Element;
121 | eraseComponent?: JSX.Element;
122 | undoComponent?: JSX.Element;
123 | clearComponent?: JSX.Element;
124 | saveComponent?: JSX.Element;
125 | strokeComponent?: (color: string) => JSX.Element;
126 | strokeSelectedComponent?: (color: string, index: number, changed: boolean) => JSX.Element;
127 | strokeWidthComponent?: (width: number) => JSX.Element;
128 |
129 | strokeColors?: { color: string }[];
130 | defaultStrokeIndex?: number;
131 | defaultStrokeWidth?: number;
132 |
133 | minStrokeWidth?: number;
134 | maxStrokeWidth?: number;
135 | strokeWidthStep?: number;
136 |
137 | /**
138 | * @param imageType "png" or "jpg"
139 | * @param includeImage default true
140 | * @param cropToImageSize default false
141 | */
142 | savePreference?: () => {
143 | folder: string;
144 | filename: string;
145 | transparent: boolean;
146 | imageType: ImageType;
147 | includeImage?: boolean;
148 | cropToImageSize?: boolean;
149 | };
150 | onSketchSaved?: (result: boolean, path: string) => void;
151 |
152 | /**
153 | * {
154 | * path: string,
155 | * directory: string,
156 | * mode: 'AspectFill' | 'AspectFit' | 'ScaleToFill'
157 | * }
158 | */
159 | localSourceImage?: LocalSourceImage;
160 | }
161 |
162 | export default class RNSketchCanvas extends React.Component {
163 | clear(): void;
164 | undo(): number;
165 | addPath(data: Path): void;
166 | deletePath(id: number): void;
167 | save(): void;
168 | nextStrokeWidth(): void;
169 |
170 | static MAIN_BUNDLE: string;
171 | static DOCUMENT: string;
172 | static LIBRARY: string;
173 | static CACHES: string;
174 | static TEMPORARY: string;
175 | static ROAMING: string;
176 | static LOCAL: string;
177 | }
178 |
--------------------------------------------------------------------------------
/example/ios/example/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
25 |
31 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/example/__windows_tests__/Draw-color-test.js:
--------------------------------------------------------------------------------
1 | import { driver, By2 } from 'selenium-appium';
2 | import { until, Origin } from 'selenium-webdriver';
3 | import { PNG } from 'pngjs';
4 | import pixelmatch from 'pixelmatch';
5 |
6 | const setup = require('../jest-windows/driver.setup');
7 | jest.setTimeout(60000);
8 |
9 |
10 | function pngFromBase64(base64) {
11 | const pngBuffer = Buffer.from(base64, 'base64');
12 | return PNG.sync.read(pngBuffer);
13 | };
14 |
15 | const pixelThreshold = 10; // Allow 10 pixel difference, to account for anti-aliasing differences.
16 | function pixelDiffPNGs(img1, img2) {
17 | return pixelmatch(img1.data, img2.data, null, img1.width, img1.height);
18 | }
19 |
20 | beforeAll(() => {
21 | return driver.startWithCapabilities(setup.capabilites);
22 | });
23 |
24 | afterAll(() => {
25 | return driver.quit();
26 | });
27 |
28 | describe('Test draw', () => {
29 |
30 | test('Draw line', async () => {
31 | await driver.wait(until.elementLocated(By2.nativeName('- Example 2 -')));
32 |
33 | // Set to specific size, so that drawing is expectable.
34 | await driver.manage().window().setRect({x:0,y:0,width:500,height:500});
35 | await By2.nativeName('- Example 2 -').click();
36 | await(driver.sleep(1000));
37 |
38 | await By2.nativeName('Red').click();
39 | await(driver.sleep(1000));
40 |
41 | let screenshot_before_drawing = pngFromBase64(await driver.takeScreenshot());
42 |
43 | // Have to use bridge, since WinAppDriver doesn't support mouse movement directly.
44 | let builder = driver.actions({bridge: true});
45 |
46 | let drawAction = builder
47 | .move({x:100, y:-100, origin: Origin.POINTER})
48 | .press()
49 | .move({x:100, y:-100, origin: Origin.POINTER})
50 | .release();
51 | drawAction.perform();
52 | await(driver.sleep(1000));
53 |
54 | let screenshot_after_drawing = pngFromBase64(await driver.takeScreenshot());
55 | expect(pixelDiffPNGs(screenshot_before_drawing, screenshot_after_drawing)).toBeGreaterThanOrEqual(pixelThreshold);
56 |
57 | await By2.nativeName('Close').click();
58 | await(driver.sleep(1000));
59 | });
60 |
61 | test('Clear clears line', async () => {
62 | await driver.wait(until.elementLocated(By2.nativeName('- Example 1 -')));
63 |
64 | // Set to specific size, so that drawing is expectable.
65 | await driver.manage().window().setRect({x:0,y:0,width:500,height:500});
66 | await By2.nativeName('- Example 1 -').click();
67 | await(driver.sleep(1000));
68 |
69 | let screenshot_before_drawing = pngFromBase64(await driver.takeScreenshot());
70 |
71 | // Have to use bridge, since WinAppDriver doesn't support mouse movement directly.
72 | let builder = driver.actions({bridge: true});
73 |
74 | let drawAction = builder
75 | .move({x:0, y:50, origin: Origin.POINTER})
76 | .press()
77 | .move({x:100, y:100, origin: Origin.POINTER})
78 | .release();
79 | drawAction.perform();
80 | await(driver.sleep(1000));
81 |
82 | let screenshot_after_drawing = pngFromBase64(await driver.takeScreenshot());
83 | expect(pixelDiffPNGs(screenshot_before_drawing, screenshot_after_drawing)).toBeGreaterThanOrEqual(pixelThreshold);
84 |
85 | await By2.nativeName('Clear').click();
86 | await(driver.sleep(1000));
87 |
88 | let screenshot_after_clearing = pngFromBase64(await driver.takeScreenshot());
89 | expect(pixelDiffPNGs(screenshot_before_drawing, screenshot_after_clearing)).toBeLessThanOrEqual(pixelThreshold);
90 |
91 | await By2.nativeName('Close').click();
92 | await(driver.sleep(1000));
93 | });
94 |
95 | test('Undo line works', async () => {
96 | await driver.wait(until.elementLocated(By2.nativeName('- Example 1 -')));
97 |
98 | // Set to specific size, so that drawing is expectable.
99 | await driver.manage().window().setRect({x:0,y:0,width:500,height:500});
100 | await By2.nativeName('- Example 1 -').click();
101 | await(driver.sleep(1000));
102 |
103 | let screenshot_before_drawing = pngFromBase64(await driver.takeScreenshot());
104 |
105 | // Have to use bridge, since WinAppDriver doesn't support mouse movement directly.
106 | let builder = driver.actions({bridge: true});
107 |
108 | let drawAction = builder
109 | .move({x:-50, y:0, origin: Origin.POINTER})
110 | .press()
111 | .move({x:50, y:50, origin: Origin.POINTER})
112 | .release();
113 | drawAction.perform();
114 | await(driver.sleep(1000));
115 |
116 | let screenshot_after_drawing_first_line = pngFromBase64(await driver.takeScreenshot());
117 | expect(pixelDiffPNGs(screenshot_before_drawing, screenshot_after_drawing_first_line)).toBeGreaterThanOrEqual(pixelThreshold);
118 |
119 | drawAction.perform();
120 | await(driver.sleep(1000));
121 |
122 | let screenshot_after_drawing_second_line = pngFromBase64(await driver.takeScreenshot());
123 |
124 | expect(pixelDiffPNGs(screenshot_before_drawing, screenshot_after_drawing_second_line)).toBeGreaterThanOrEqual(pixelThreshold);
125 | expect(pixelDiffPNGs(screenshot_after_drawing_first_line, screenshot_after_drawing_second_line)).toBeGreaterThanOrEqual(pixelThreshold);
126 |
127 | await By2.nativeName('Undo').click();
128 | await(driver.sleep(1000));
129 |
130 | let screenshot_after_first_undo = pngFromBase64(await driver.takeScreenshot());
131 | expect(pixelDiffPNGs(screenshot_after_first_undo, screenshot_after_drawing_first_line)).toBeLessThanOrEqual(pixelThreshold);
132 |
133 | await By2.nativeName('Undo').click();
134 | await(driver.sleep(1000));
135 |
136 | let screenshot_after_second_undo = pngFromBase64(await driver.takeScreenshot());
137 | expect(pixelDiffPNGs(screenshot_after_second_undo, screenshot_before_drawing)).toBeLessThanOrEqual(pixelThreshold);
138 |
139 | await By2.nativeName('Close').click();
140 | await(driver.sleep(1000));
141 | });
142 |
143 | })
144 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ] ; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ] ; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
109 | MAX_FD_LIMIT=`ulimit -H -n`
110 | if [ $? -eq 0 ] ; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ] ; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin or MSYS, switch paths to Windows format before running java
129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
132 | JAVACMD=`cygpath --unix "$JAVACMD"`
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
136 | SEP=""
137 | for dir in $ROOTDIRSRAW ; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@" ; do
149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
154 | else
155 | eval `echo args$i`="\"$arg\""
156 | fi
157 | i=`expr $i + 1`
158 | done
159 | case $i in
160 | 0) set -- ;;
161 | 1) set -- "$args0" ;;
162 | 2) set -- "$args0" "$args1" ;;
163 | 3) set -- "$args0" "$args1" "$args2" ;;
164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save () {
175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
176 | echo " "
177 | }
178 | APP_ARGS=`save "$@"`
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | exec "$JAVACMD" "$@"
184 |
--------------------------------------------------------------------------------
/windows/RNSketchCanvas/SketchData.cpp:
--------------------------------------------------------------------------------
1 | #include "pch.h"
2 | #include "SketchData.h"
3 | #include "Utility.h"
4 |
5 | namespace winrt
6 | {
7 | using namespace Microsoft::Graphics::Canvas;
8 | using namespace Microsoft::Graphics::Canvas::Brushes;
9 | using namespace Microsoft::Graphics::Canvas::Geometry;
10 | using namespace Windows::Foundation;
11 | using namespace Windows::Foundation::Numerics;
12 | using namespace Windows::UI;
13 | using namespace Windows::UI::Xaml;
14 | /*using namespace Windows::UI::Xaml::Shapes;
15 | using namespace Windows::UI::Xaml::Controls;
16 | using namespace Windows::UI::Xaml::Media;*/
17 | }
18 |
19 | namespace winrt::RNSketchCanvas::implementation
20 | {
21 |
22 | std::optional SketchData::mStrokeStyle = std::nullopt;
23 |
24 | float2 SketchData::midPoint(const float2& p1, const float2& p2)
25 | {
26 | return float2((p1.x + p2.x) * .5f, (p1.y + p2.y) * .5f);
27 | }
28 |
29 | SketchData::SketchData(int id, Color strokeColor, float strokeWidth)
30 | {
31 | this->id = id;
32 | this->strokeColor = strokeColor;
33 | this->strokeWidth = strokeWidth;
34 | this->isTranslucent = strokeColor.A != 255 && !Utility::isColorTransparent(strokeColor);
35 | mPath.reset(); // Geometry has to be created with something.
36 | }
37 |
38 | SketchData::SketchData(int id, Color strokeColor, float strokeWidth, std::vector points)
39 | {
40 | this->id = id;
41 | this->strokeColor = strokeColor;
42 | this->strokeWidth = strokeWidth;
43 | this->points.insert(std::end(this->points), std::begin(points), std::end(points));
44 | this->isTranslucent = strokeColor.A != 255 && !Utility::isColorTransparent(strokeColor);
45 | mPath = this->isTranslucent ? evaluatePath() : nullptr;
46 | }
47 |
48 | void SketchData::addPoint(const float2& p)
49 | {
50 | points.push_back(p);
51 | int pointsCount = points.size();
52 | if (isTranslucent)
53 | {
54 | if (pointsCount >= 3)
55 | {
56 | addPointToPath(
57 | points[pointsCount - 3],
58 | points[pointsCount - 2],
59 | p);
60 | } else if (pointsCount >= 2)
61 | {
62 | addPointToPath(points[0], points[0], p);
63 | } else
64 | {
65 | addPointToPath(p, p, p);
66 | }
67 | } else
68 | {
69 | if (pointsCount >= 3)
70 | {
71 | float2 a = points[pointsCount - 3];
72 | float2 b = points[pointsCount - 2];
73 | float2 c = p;
74 | float2 prevMid = midPoint(a, b);
75 | float2 currentMid = midPoint(b, c);
76 |
77 | } else if (pointsCount >= 2)
78 | {
79 | float2 a = points[pointsCount - 2];
80 | float2 b = p;
81 | float2 mid = midPoint(a, b);
82 | }
83 | }
84 | }
85 |
86 | void SketchData::drawLastPoint(const CanvasDrawingSession& canvasDS)
87 | {
88 | int pointsCount = points.size();
89 | if (pointsCount < 1)
90 | {
91 | return;
92 | }
93 | draw(canvasDS, pointsCount - 1);
94 | }
95 |
96 | void SketchData::draw(const CanvasDrawingSession& canvasDS)
97 | {
98 | canvasDS.Blend(CanvasBlend::SourceOver);
99 | bool isErase = Utility::isColorTransparent(strokeColor);
100 | canvasDS.Blend(isErase ? CanvasBlend::Copy : CanvasBlend::SourceOver);
101 |
102 | if (this->isTranslucent)
103 | {
104 | canvasDS.DrawGeometry(mPath.value(), strokeColor, strokeWidth, getStrokeStyle());
105 | } else
106 | {
107 | int pointsCount = points.size();
108 | for (int i = 0; i < pointsCount; i++)
109 | {
110 | draw(canvasDS, i);
111 | }
112 | }
113 | }
114 |
115 | void SketchData::draw(const CanvasDrawingSession& canvasDS, int pointIndex)
116 | {
117 | int pointsCount = points.size();
118 | if (pointIndex >= pointsCount)
119 | {
120 | return;
121 | }
122 |
123 | bool isErase = Utility::isColorTransparent(strokeColor);
124 | canvasDS.Blend(isErase ? CanvasBlend::Copy : CanvasBlend::SourceOver);
125 |
126 | if (pointsCount >= 3 && pointIndex >= 2)
127 | {
128 | float2 a = points[pointIndex - 2];
129 | float2 b = points[pointIndex - 1];
130 | float2 c = points[pointIndex];
131 | float2 prevMid = midPoint(a, b);
132 | float2 currMid = midPoint(b, c);
133 |
134 | // Draw a curve
135 | CanvasPathBuilder path = CanvasPathBuilder(canvasDS.Device());
136 | path.BeginFigure(prevMid);
137 | path.AddQuadraticBezier(b, currMid);
138 | path.EndFigure(CanvasFigureLoop::Open);
139 | canvasDS.DrawGeometry(CanvasGeometry::CreatePath(path), strokeColor, strokeWidth, getStrokeStyle());
140 | } else if (pointsCount >= 2 && pointIndex >= 1)
141 | {
142 | float2 a = points[pointIndex - 1];
143 | float2 b = points[pointIndex];
144 | float2 mid = midPoint(a, b);
145 |
146 | // Draw a line to the middle of points a and b
147 | // This is so the next draw which uses a curve looks correct and continues from there
148 | canvasDS.DrawLine(a, mid, strokeColor, strokeWidth, getStrokeStyle());
149 | } else if (pointsCount >= 1)
150 | {
151 | float2 a = points[pointIndex];
152 |
153 | // Draw a single point
154 | canvasDS.DrawLine(a, a, strokeColor, strokeWidth, getStrokeStyle());
155 | }
156 | }
157 |
158 | CanvasStrokeStyle SketchData::getStrokeStyle()
159 | {
160 | if (!SketchData::mStrokeStyle.has_value())
161 | {
162 |
163 | CanvasStrokeStyle style;
164 | style.DashStyle(CanvasDashStyle::Solid);
165 | style.StartCap(CanvasCapStyle::Round);
166 | style.EndCap(CanvasCapStyle::Round);
167 | style.DashCap(CanvasCapStyle::Round);
168 | SketchData::mStrokeStyle = style;
169 | }
170 | return SketchData::mStrokeStyle.value();
171 | }
172 |
173 | CanvasGeometry SketchData::evaluatePath()
174 | {
175 | int pointsCount = points.size();
176 | CanvasPathBuilder path(CanvasDevice::GetSharedDevice());
177 | for (int pointIndex = 0; pointIndex < pointsCount; pointIndex++)
178 | {
179 | if (pointsCount >= 3 && pointIndex >= 2)
180 | {
181 | float2 a = points[pointIndex - 2];
182 | float2 b = points[pointIndex - 1];
183 | float2 c = points[pointIndex];
184 | float2 prevMid = midPoint(a, b);
185 | float2 currMid = midPoint(b, c);
186 |
187 | // Draw a curve
188 | path.BeginFigure(prevMid);
189 | path.AddQuadraticBezier(b, currMid);
190 | path.EndFigure(CanvasFigureLoop::Open);
191 | } else if (pointsCount >= 2 && pointIndex >= 1)
192 | {
193 | float2 a = points[pointIndex - 1];
194 | float2 b = points[pointIndex];
195 | float2 mid = midPoint(a, b);
196 |
197 | // Draw a line to the middle of points a and b
198 | // This is so the next draw which uses a curve looks correct and continues from there
199 | path.BeginFigure(a);
200 | path.AddLine(mid);
201 | path.EndFigure(CanvasFigureLoop::Open);
202 | } else if (pointsCount >= 1)
203 | {
204 | float2 a = points[pointIndex];
205 |
206 | // Draw a single point
207 | path.BeginFigure(a);
208 | path.AddLine(a);
209 | path.EndFigure(CanvasFigureLoop::Open);
210 | }
211 | }
212 |
213 | return CanvasGeometry::CreatePath(path);
214 | }
215 |
216 | void SketchData::addPointToPath(
217 | const float2& tPoint,
218 | const float2& pPoint,
219 | const float2& point
220 | )
221 | {
222 | CanvasPathBuilder path = CanvasPathBuilder(CanvasDevice::GetSharedDevice());
223 | float2 mid1 = midPoint(pPoint, tPoint);
224 | float2 mid2 = midPoint(point, pPoint);
225 | path.BeginFigure(mid1);
226 | path.AddQuadraticBezier(pPoint, mid2);
227 | path.EndFigure(CanvasFigureLoop::Open);
228 | CanvasGeometry geometry = CanvasGeometry::CreatePath(path);
229 | if (mPath.has_value())
230 | {
231 | mPath = CanvasGeometry::CreateGroup(CanvasDevice::GetSharedDevice(), { mPath.value(), geometry });
232 | } else
233 | {
234 | mPath = geometry;
235 | }
236 | }
237 |
238 | }
239 |
--------------------------------------------------------------------------------
/ios/RNSketchCanvas/RNSketchCanvas/RNSketchData.m:
--------------------------------------------------------------------------------
1 | //
2 | // RNSketchCanvasData.m
3 | // RNSketchCanvas
4 | //
5 | // Created by terry on 03/08/2017.
6 | // Copyright © 2017 Terry. All rights reserved.
7 | //
8 |
9 | #import "RNSketchData.h"
10 | #import "Utility.h"
11 |
12 | @interface RNSketchData ()
13 |
14 | @property (nonatomic, readwrite) int pathId;
15 | @property (nonatomic, readwrite) CGFloat strokeWidth;
16 | @property (nonatomic, readwrite) UIColor* strokeColor;
17 | @property (nonatomic, readwrite) NSMutableArray *points;
18 |
19 | @end
20 |
21 | @implementation RNSketchData
22 | {
23 | CGRect _dirty;
24 | UIBezierPath *_path;
25 | }
26 |
27 | - (instancetype)initWithId:(int) pathId strokeColor:(UIColor*) strokeColor strokeWidth:(int) strokeWidth {
28 | self = [super init];
29 | if (self) {
30 | _pathId = pathId;
31 | _strokeColor = strokeColor;
32 | _strokeWidth = strokeWidth;
33 | _points = [NSMutableArray new];
34 | _isTranslucent = CGColorGetComponents(strokeColor.CGColor)[3] != 1.0 &&
35 | ![Utility isSameColor:strokeColor color:[UIColor clearColor]];
36 | _path = _isTranslucent ? [UIBezierPath new] : nil;
37 | _dirty = CGRectZero;
38 | }
39 | return self;
40 | }
41 |
42 | - (instancetype)initWithId:(int) pathId strokeColor:(UIColor*) strokeColor strokeWidth:(int) strokeWidth points: (NSArray*) points {
43 | self = [super init];
44 | if (self) {
45 | _pathId = pathId;
46 | _strokeColor = strokeColor;
47 | _strokeWidth = strokeWidth;
48 | _points = [points mutableCopy];
49 | _isTranslucent = CGColorGetComponents(strokeColor.CGColor)[3] != 1.0 &&
50 | ![Utility isSameColor:strokeColor color:[UIColor clearColor]];
51 | _path = _isTranslucent ? [self evaluatePath] : nil;
52 | _dirty = CGRectZero;
53 | }
54 | return self;
55 | }
56 |
57 | - (CGRect)addPoint:(CGPoint) point {
58 | [_points addObject: [NSValue valueWithCGPoint: point]];
59 |
60 | CGRect updateRect;
61 |
62 | NSUInteger pointsCount = _points.count;
63 |
64 | if (_isTranslucent) {
65 | if (pointsCount >= 3) {
66 | [Utility addPointToPath: _path
67 | toPoint: point
68 | tertiaryPoint: [_points[_points.count - 3] CGPointValue]
69 | previousPoint:[_points[_points.count - 2] CGPointValue]];
70 | } else if (pointsCount >= 2) {
71 | [Utility addPointToPath: _path
72 | toPoint: point
73 | tertiaryPoint: [_points[0] CGPointValue]
74 | previousPoint: [_points[0] CGPointValue]];
75 | } else {
76 | [Utility addPointToPath: _path toPoint: point tertiaryPoint: point previousPoint: point];
77 | }
78 |
79 | CGFloat x = point.x, y = point.y;
80 | _dirty = CGRectIsEmpty(_dirty) ? CGRectMake(x, y, 1, 1) : CGRectUnion(_dirty, CGRectMake(x, y, 1, 1));
81 | updateRect = CGRectInset(_dirty, -_strokeWidth * 2, -_strokeWidth * 2);
82 | } else {
83 | if (pointsCount >= 3) {
84 | CGPoint a = _points[pointsCount - 3].CGPointValue;
85 | CGPoint b = _points[pointsCount - 2].CGPointValue;
86 | CGPoint c = point;
87 | CGPoint prevMid = midPoint(a, b);
88 | CGPoint currentMid = midPoint(b, c);
89 |
90 | updateRect = CGRectMake(prevMid.x, prevMid.y, 0, 0);
91 | updateRect = CGRectUnion(updateRect, CGRectMake(b.x, b.y, 0, 0));
92 | updateRect = CGRectUnion(updateRect, CGRectMake(currentMid.x, currentMid.y, 0, 0));
93 | } else if (pointsCount >= 2) {
94 | CGPoint a = _points[pointsCount - 2].CGPointValue;
95 | CGPoint b = point;
96 | CGPoint mid = midPoint(a, b);
97 |
98 | updateRect = CGRectMake(a.x, a.y, 0, 0);
99 | updateRect = CGRectUnion(updateRect, CGRectMake(mid.x, mid.y, 0, 0));
100 | } else {
101 | updateRect = CGRectMake(point.x, point.y, 0, 0);
102 | }
103 |
104 | updateRect = CGRectInset(updateRect, -_strokeWidth * 2, -_strokeWidth * 2);
105 | }
106 |
107 | return updateRect;
108 | }
109 |
110 | - (void)drawLastPointInContext:(CGContextRef)context {
111 | NSUInteger pointsCount = _points.count;
112 | if (pointsCount < 1) {
113 | return;
114 | };
115 |
116 | [self drawInContext:context pointIndex:pointsCount - 1];
117 | }
118 | - (void)drawInContext:(CGContextRef)context {
119 | if (_isTranslucent) {
120 | CGContextSetLineWidth(context, _strokeWidth);
121 | CGContextSetLineCap(context, kCGLineCapRound);
122 | CGContextSetLineJoin(context, kCGLineJoinRound);
123 | CGContextSetStrokeColorWithColor(context, [_strokeColor CGColor]);
124 | CGContextSetBlendMode(context, kCGBlendModeNormal);
125 |
126 | CGContextAddPath(context, _path.CGPath);
127 | CGContextStrokePath(context);
128 | } else {
129 | NSUInteger pointsCount = _points.count;
130 | for (NSUInteger i = 0; i < pointsCount; i++) {
131 | @autoreleasepool {
132 | [self drawInContext:context pointIndex:i];
133 | }
134 | }
135 | }
136 | }
137 |
138 | - (void)drawInContext:(CGContextRef)context pointIndex:(NSUInteger)pointIndex {
139 | NSUInteger pointsCount = _points.count;
140 | if (pointIndex >= pointsCount) {
141 | return;
142 | };
143 |
144 | BOOL isErase = [Utility isSameColor:_strokeColor color:[UIColor clearColor]];
145 |
146 | CGContextSetStrokeColorWithColor(context, _strokeColor.CGColor);
147 | CGContextSetLineWidth(context, _strokeWidth);
148 | CGContextSetLineCap(context, kCGLineCapRound);
149 | CGContextSetLineJoin(context, kCGLineJoinRound);
150 | CGContextSetBlendMode(context, isErase ? kCGBlendModeClear : kCGBlendModeNormal);
151 | CGContextBeginPath(context);
152 |
153 | if (pointsCount >= 3 && pointIndex >= 2) {
154 | CGPoint a = _points[pointIndex - 2].CGPointValue;
155 | CGPoint b = _points[pointIndex - 1].CGPointValue;
156 | CGPoint c = _points[pointIndex].CGPointValue;
157 | CGPoint prevMid = midPoint(a, b);
158 | CGPoint currentMid = midPoint(b, c);
159 |
160 | // Draw a curve
161 | CGContextMoveToPoint(context, prevMid.x, prevMid.y);
162 | CGContextAddQuadCurveToPoint(context, b.x, b.y, currentMid.x, currentMid.y);
163 | } else if (pointsCount >= 2 && pointIndex >= 1) {
164 | CGPoint a = _points[pointIndex - 1].CGPointValue;
165 | CGPoint b = _points[pointIndex].CGPointValue;
166 | CGPoint mid = midPoint(a, b);
167 |
168 | // Draw a line to the middle of points a and b
169 | // This is so the next draw which uses a curve looks correct and continues from there
170 | CGContextMoveToPoint(context, a.x, a.y);
171 | CGContextAddLineToPoint(context, mid.x, mid.y);
172 | } else if (pointsCount >= 1) {
173 | CGPoint a = _points[pointIndex].CGPointValue;
174 |
175 | // Draw a single point
176 | CGContextMoveToPoint(context, a.x, a.y);
177 | CGContextAddLineToPoint(context, a.x, a.y);
178 | }
179 |
180 | CGContextStrokePath(context);
181 | }
182 |
183 | // Translucent
184 | - (UIBezierPath*) evaluatePath {
185 | NSUInteger pointsCount = _points.count;
186 | UIBezierPath *path = [UIBezierPath new];
187 |
188 | for(NSUInteger pointIndex=0; pointIndex= 3 && pointIndex >= 2) {
190 | CGPoint a = _points[pointIndex - 2].CGPointValue;
191 | CGPoint b = _points[pointIndex - 1].CGPointValue;
192 | CGPoint c = _points[pointIndex].CGPointValue;
193 | CGPoint prevMid = midPoint(a, b);
194 | CGPoint currentMid = midPoint(b, c);
195 |
196 | // Draw a curve
197 | [path moveToPoint:prevMid];
198 | [path addQuadCurveToPoint:currentMid controlPoint:b];
199 | } else if (pointsCount >= 2 && pointIndex >= 1) {
200 | CGPoint a = _points[pointIndex - 1].CGPointValue;
201 | CGPoint b = _points[pointIndex].CGPointValue;
202 | CGPoint mid = midPoint(a, b);
203 |
204 | // Draw a line to the middle of points a and b
205 | // This is so the next draw which uses a curve looks correct and continues from there
206 | [path moveToPoint:a];
207 | [path addLineToPoint:mid];
208 | } else if (pointsCount >= 1) {
209 | CGPoint a = _points[pointIndex].CGPointValue;
210 |
211 | // Draw a single point
212 | [path moveToPoint:a];
213 | [path addLineToPoint:a];
214 | }
215 | }
216 | return path;
217 | }
218 |
219 |
220 | @end
221 |
--------------------------------------------------------------------------------
/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchData.java:
--------------------------------------------------------------------------------
1 | package com.terrylinla.rnsketchcanvas;
2 |
3 | import android.graphics.Canvas;
4 | import android.graphics.Color;
5 | import android.graphics.Paint;
6 | import android.graphics.Path;
7 | import android.graphics.PointF;
8 | import android.graphics.PorterDuff;
9 | import android.graphics.PorterDuffXfermode;
10 | import android.graphics.Rect;
11 | import android.graphics.RectF;
12 |
13 | import java.util.ArrayList;
14 |
15 | public class SketchData {
16 | public final ArrayList points = new ArrayList();
17 | public final int id, strokeColor;
18 | public final float strokeWidth;
19 | public final boolean isTranslucent;
20 |
21 | private Paint mPaint;
22 | private Path mPath;
23 | private RectF mDirty = null;
24 |
25 | public static PointF midPoint(PointF p1, PointF p2) {
26 | return new PointF((p1.x + p2.x) * 0.5f, (p1.y + p2.y) * 0.5f);
27 | }
28 |
29 | public SketchData(int id, int strokeColor, float strokeWidth) {
30 | this.id = id;
31 | this.strokeColor = strokeColor;
32 | this.strokeWidth = strokeWidth;
33 | this.isTranslucent = ((strokeColor >> 24) & 0xff) != 255 && strokeColor != Color.TRANSPARENT;
34 | mPath = this.isTranslucent ? new Path() : null;
35 | }
36 |
37 | public SketchData(int id, int strokeColor, float strokeWidth, ArrayList points) {
38 | this.id = id;
39 | this.strokeColor = strokeColor;
40 | this.strokeWidth = strokeWidth;
41 | this.points.addAll(points);
42 | this.isTranslucent = ((strokeColor >> 24) & 0xff) != 255 && strokeColor != Color.TRANSPARENT;
43 | mPath = this.isTranslucent ? evaluatePath() : null;
44 | }
45 |
46 | public Rect addPoint(PointF p) {
47 | points.add(p);
48 |
49 | RectF updateRect;
50 |
51 | int pointsCount = points.size();
52 |
53 | if (this.isTranslucent) {
54 | if (pointsCount >= 3) {
55 | addPointToPath(mPath,
56 | this.points.get(pointsCount - 3),
57 | this.points.get(pointsCount - 2),
58 | p);
59 | } else if (pointsCount >= 2) {
60 | addPointToPath(mPath, this.points.get(0), this.points.get(0), p);
61 | } else {
62 | addPointToPath(mPath, p, p, p);
63 | }
64 |
65 | float x = p.x, y = p.y;
66 | if (mDirty == null) {
67 | mDirty = new RectF(x, y, x + 1, y + 1);
68 | updateRect = new RectF(x - this.strokeWidth, y - this.strokeWidth,
69 | x + this.strokeWidth, y + this.strokeWidth);
70 | } else {
71 | mDirty.union(x, y);
72 | updateRect = new RectF(
73 | mDirty.left - this.strokeWidth, mDirty.top - this.strokeWidth,
74 | mDirty.right + this.strokeWidth, mDirty.bottom + this.strokeWidth
75 | );
76 | }
77 | } else {
78 | if (pointsCount >= 3) {
79 | PointF a = points.get(pointsCount - 3);
80 | PointF b = points.get(pointsCount - 2);
81 | PointF c = p;
82 | PointF prevMid = midPoint(a, b);
83 | PointF currentMid = midPoint(b, c);
84 |
85 | updateRect = new RectF(prevMid.x, prevMid.y, prevMid.x, prevMid.y);
86 | updateRect.union(b.x, b.y);
87 | updateRect.union(currentMid.x, currentMid.y);
88 | } else if (pointsCount >= 2) {
89 | PointF a = points.get(pointsCount - 2);
90 | PointF b = p;
91 | PointF mid = midPoint(a, b);
92 |
93 | updateRect = new RectF(a.x, a.y, a.x, a.y);
94 | updateRect.union(mid.x, mid.y);
95 | } else {
96 | updateRect = new RectF(p.x, p.y, p.x, p.y);
97 | }
98 |
99 | updateRect.inset(-strokeWidth * 2, -strokeWidth * 2);
100 |
101 | }
102 | Rect integralRect = new Rect();
103 | updateRect.roundOut(integralRect);
104 |
105 | return integralRect;
106 | }
107 |
108 | public void drawLastPoint(Canvas canvas) {
109 | int pointsCount = points.size();
110 | if (pointsCount < 1) {
111 | return;
112 | }
113 |
114 | draw(canvas, pointsCount - 1);
115 | }
116 |
117 | public void draw(Canvas canvas) {
118 | if (this.isTranslucent) {
119 | canvas.drawPath(mPath, getPaint());
120 | } else {
121 | int pointsCount = points.size();
122 | for (int i = 0; i < pointsCount; i++) {
123 | draw(canvas, i);
124 | }
125 | }
126 | }
127 |
128 | private Paint getPaint() {
129 | if (mPaint == null) {
130 | boolean isErase = strokeColor == Color.TRANSPARENT;
131 |
132 | mPaint = new Paint();
133 | mPaint.setColor(strokeColor);
134 | mPaint.setStrokeWidth(strokeWidth);
135 | mPaint.setStyle(Paint.Style.STROKE);
136 | mPaint.setStrokeCap(Paint.Cap.ROUND);
137 | mPaint.setStrokeJoin(Paint.Join.ROUND);
138 | mPaint.setAntiAlias(true);
139 | mPaint.setXfermode(new PorterDuffXfermode(isErase ? PorterDuff.Mode.CLEAR : PorterDuff.Mode.SRC_OVER));
140 | }
141 | return mPaint;
142 | }
143 |
144 | private void draw(Canvas canvas, int pointIndex) {
145 | int pointsCount = points.size();
146 | if (pointIndex >= pointsCount) {
147 | return;
148 | }
149 |
150 | if (pointsCount >= 3 && pointIndex >= 2) {
151 | PointF a = points.get(pointIndex - 2);
152 | PointF b = points.get(pointIndex - 1);
153 | PointF c = points.get(pointIndex);
154 | PointF prevMid = midPoint(a, b);
155 | PointF currentMid = midPoint(b, c);
156 |
157 | // Draw a curve
158 | Path path = new Path();
159 | path.moveTo(prevMid.x, prevMid.y);
160 | path.quadTo(b.x, b.y, currentMid.x, currentMid.y);
161 |
162 | canvas.drawPath(path, getPaint());
163 | } else if (pointsCount >= 2 && pointIndex >= 1) {
164 | PointF a = points.get(pointIndex - 1);
165 | PointF b = points.get(pointIndex);
166 | PointF mid = midPoint(a, b);
167 |
168 | // Draw a line to the middle of points a and b
169 | // This is so the next draw which uses a curve looks correct and continues from there
170 | canvas.drawLine(a.x, a.y, mid.x, mid.y, getPaint());
171 | } else if (pointsCount >= 1) {
172 | PointF a = points.get(pointIndex);
173 |
174 | // Draw a single point
175 | canvas.drawPoint(a.x, a.y, getPaint());
176 | }
177 | }
178 |
179 | private Path evaluatePath() {
180 | int pointsCount = points.size();
181 | Path path = new Path();
182 |
183 | for(int pointIndex=0; pointIndex= 3 && pointIndex >= 2) {
185 | PointF a = points.get(pointIndex - 2);
186 | PointF b = points.get(pointIndex - 1);
187 | PointF c = points.get(pointIndex);
188 | PointF prevMid = midPoint(a, b);
189 | PointF currentMid = midPoint(b, c);
190 |
191 | // Draw a curve
192 | path.moveTo(prevMid.x, prevMid.y);
193 | path.quadTo(b.x, b.y, currentMid.x, currentMid.y);
194 | } else if (pointsCount >= 2 && pointIndex >= 1) {
195 | PointF a = points.get(pointIndex - 1);
196 | PointF b = points.get(pointIndex);
197 | PointF mid = midPoint(a, b);
198 |
199 | // Draw a line to the middle of points a and b
200 | // This is so the next draw which uses a curve looks correct and continues from there
201 | path.moveTo(a.x, a.y);
202 | path.lineTo(mid.x, mid.y);
203 | } else if (pointsCount >= 1) {
204 | PointF a = points.get(pointIndex);
205 |
206 | // Draw a single point
207 | path.moveTo(a.x, a.y);
208 | path.lineTo(a.x, a.y);
209 | }
210 | }
211 | return path;
212 | }
213 |
214 | private void addPointToPath(Path path, PointF tPoint, PointF pPoint, PointF point) {
215 | PointF mid1 = new PointF((pPoint.x + tPoint.x) * 0.5f, (pPoint.y + tPoint.y) * 0.5f);
216 | PointF mid2 = new PointF((point.x + pPoint.x) * 0.5f, (point.y + pPoint.y) * 0.5f);
217 | path.moveTo(mid1.x, mid1.y);
218 | path.quadTo(pPoint.x, pPoint.y, mid2.x, mid2.y);
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation. If none specified and
19 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
20 | * // default. Can be overridden with ENTRY_FILE environment variable.
21 | * entryFile: "index.android.js",
22 | *
23 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
24 | * bundleCommand: "ram-bundle",
25 | *
26 | * // whether to bundle JS and assets in debug mode
27 | * bundleInDebug: false,
28 | *
29 | * // whether to bundle JS and assets in release mode
30 | * bundleInRelease: true,
31 | *
32 | * // whether to bundle JS and assets in another build variant (if configured).
33 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
34 | * // The configuration property can be in the following formats
35 | * // 'bundleIn${productFlavor}${buildType}'
36 | * // 'bundleIn${buildType}'
37 | * // bundleInFreeDebug: true,
38 | * // bundleInPaidRelease: true,
39 | * // bundleInBeta: true,
40 | *
41 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
42 | * // for example: to disable dev mode in the staging build type (if configured)
43 | * devDisabledInStaging: true,
44 | * // The configuration property can be in the following formats
45 | * // 'devDisabledIn${productFlavor}${buildType}'
46 | * // 'devDisabledIn${buildType}'
47 | *
48 | * // the root of your project, i.e. where "package.json" lives
49 | * root: "../../",
50 | *
51 | * // where to put the JS bundle asset in debug mode
52 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
53 | *
54 | * // where to put the JS bundle asset in release mode
55 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
56 | *
57 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
58 | * // require('./image.png')), in debug mode
59 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
60 | *
61 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
62 | * // require('./image.png')), in release mode
63 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
64 | *
65 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
66 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
67 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
68 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
69 | * // for example, you might want to remove it from here.
70 | * inputExcludes: ["android/**", "ios/**"],
71 | *
72 | * // override which node gets called and with what additional arguments
73 | * nodeExecutableAndArgs: ["node"],
74 | *
75 | * // supply additional arguments to the packager
76 | * extraPackagerArgs: []
77 | * ]
78 | */
79 |
80 | project.ext.react = [
81 | enableHermes: false, // clean and rebuild if changing
82 | ]
83 |
84 | apply from: "../../node_modules/react-native/react.gradle"
85 |
86 | /**
87 | * Set this to true to create two separate APKs instead of one:
88 | * - An APK that only works on ARM devices
89 | * - An APK that only works on x86 devices
90 | * The advantage is the size of the APK is reduced by about 4MB.
91 | * Upload all the APKs to the Play Store and people will download
92 | * the correct one based on the CPU architecture of their device.
93 | */
94 | def enableSeparateBuildPerCPUArchitecture = false
95 |
96 | /**
97 | * Run Proguard to shrink the Java bytecode in release builds.
98 | */
99 | def enableProguardInReleaseBuilds = false
100 |
101 | /**
102 | * The preferred build flavor of JavaScriptCore.
103 | *
104 | * For example, to use the international variant, you can use:
105 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
106 | *
107 | * The international variant includes ICU i18n library and necessary data
108 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
109 | * give correct results when using with locales other than en-US. Note that
110 | * this variant is about 6MiB larger per architecture than default.
111 | */
112 | def jscFlavor = 'org.webkit:android-jsc:+'
113 |
114 | /**
115 | * Whether to enable the Hermes VM.
116 | *
117 | * This should be set on project.ext.react and mirrored here. If it is not set
118 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
119 | * and the benefits of using Hermes will therefore be sharply reduced.
120 | */
121 | def enableHermes = project.ext.react.get("enableHermes", false);
122 |
123 | android {
124 | compileSdkVersion rootProject.ext.compileSdkVersion
125 |
126 | compileOptions {
127 | sourceCompatibility JavaVersion.VERSION_1_8
128 | targetCompatibility JavaVersion.VERSION_1_8
129 | }
130 |
131 | defaultConfig {
132 | applicationId "com.example"
133 | minSdkVersion rootProject.ext.minSdkVersion
134 | targetSdkVersion rootProject.ext.targetSdkVersion
135 | versionCode 1
136 | versionName "1.0"
137 | missingDimensionStrategy 'react-native-camera', 'general'
138 | }
139 | splits {
140 | abi {
141 | reset()
142 | enable enableSeparateBuildPerCPUArchitecture
143 | universalApk false // If true, also generate a universal APK
144 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
145 | }
146 | }
147 | signingConfigs {
148 | debug {
149 | storeFile file('debug.keystore')
150 | storePassword 'android'
151 | keyAlias 'androiddebugkey'
152 | keyPassword 'android'
153 | }
154 | }
155 | buildTypes {
156 | debug {
157 | signingConfig signingConfigs.debug
158 | }
159 | release {
160 | // Caution! In production, you need to generate your own keystore file.
161 | // see https://reactnative.dev/docs/signed-apk-android.
162 | signingConfig signingConfigs.debug
163 | minifyEnabled enableProguardInReleaseBuilds
164 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
165 | }
166 | }
167 |
168 | // applicationVariants are e.g. debug, release
169 | applicationVariants.all { variant ->
170 | variant.outputs.each { output ->
171 | // For each separate APK per architecture, set a unique version code as described here:
172 | // https://developer.android.com/studio/build/configure-apk-splits.html
173 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
174 | def abi = output.getFilter(OutputFile.ABI)
175 | if (abi != null) { // null for the universal-debug, universal-release variants
176 | output.versionCodeOverride =
177 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
178 | }
179 |
180 | }
181 | }
182 | }
183 |
184 | dependencies {
185 | implementation fileTree(dir: "libs", include: ["*.jar"])
186 | //noinspection GradleDynamicVersion
187 | implementation "com.facebook.react:react-native:+" // From node_modules
188 |
189 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
190 |
191 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
192 | exclude group:'com.facebook.fbjni'
193 | }
194 |
195 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
196 | exclude group:'com.facebook.flipper'
197 | exclude group:'com.squareup.okhttp3', module:'okhttp'
198 | }
199 |
200 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
201 | exclude group:'com.facebook.flipper'
202 | }
203 |
204 | if (enableHermes) {
205 | def hermesPath = "../../node_modules/hermes-engine/android/";
206 | debugImplementation files(hermesPath + "hermes-debug.aar")
207 | releaseImplementation files(hermesPath + "hermes-release.aar")
208 | } else {
209 | implementation jscFlavor
210 | }
211 | }
212 |
213 | // Run this once to be able to run the application with BUCK
214 | // puts all compile dependencies into folder libs for BUCK to use
215 | task copyDownloadableDepsToLibs(type: Copy) {
216 | from configurations.compile
217 | into 'libs'
218 | }
219 |
220 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
221 |
--------------------------------------------------------------------------------
/windows/RNSketchCanvas/RNSketchCanvas.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | true
6 | true
7 | true
8 | {f96593a0-46b4-47da-a15a-7a135934ce1f}
9 | RNSketchCanvas
10 | RNSketchCanvas
11 | en-US
12 | 16.0
13 | true
14 | Windows Store
15 | 10.0
16 | 10.0.18362.0
17 | 10.0.17763.0
18 |
19 |
20 |
21 | $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'node_modules\react-native-windows\package.json'))\node_modules\react-native-windows\
22 |
23 |
24 |
25 | Debug
26 | ARM
27 |
28 |
29 | Debug
30 | ARM64
31 |
32 |
33 | Debug
34 | Win32
35 |
36 |
37 | Debug
38 | x64
39 |
40 |
41 | Release
42 | ARM
43 |
44 |
45 | Release
46 | ARM64
47 |
48 |
49 | Release
50 | Win32
51 |
52 |
53 | Release
54 | x64
55 |
56 |
57 |
58 | DynamicLibrary
59 | Unicode
60 | false
61 |
62 |
63 | true
64 | true
65 |
66 |
67 | false
68 | true
69 | false
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | Use
88 | pch.h
89 | $(IntDir)pch.pch
90 | Level4
91 | %(AdditionalOptions) /bigobj
92 |
93 | /DWINRT_NO_MAKE_DETECTION %(AdditionalOptions)
94 | 28204
95 | _WINRT_DLL;%(PreprocessorDefinitions)
96 | $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)
97 |
98 |
99 | Console
100 | true
101 | RNSketchCanvas.def
102 |
103 |
104 |
105 |
106 | _DEBUG;%(PreprocessorDefinitions)
107 | ProgramDatabase
108 |
109 |
110 |
111 |
112 | NDEBUG;%(PreprocessorDefinitions)
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | ReactPackageProvider.idl
121 |
122 |
123 | RNSketchCanvas.idl
124 |
125 |
126 |
127 |
128 |
129 |
130 | Create
131 |
132 |
133 |
134 | ReactPackageProvider.idl
135 |
136 |
137 | RNSketchCanvas.idl
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 | This project references targets in your node_modules\react-native-windows folder. The missing file is {0}.
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
174 |
175 |
176 |
177 |
178 |
179 |
--------------------------------------------------------------------------------
/example/windows/example/example.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | true
6 | true
7 | true
8 | {bbf8c8ac-a17b-4eed-ba00-c3aedccd6f74}
9 | example
10 | example
11 | en-US
12 | 16.0
13 | true
14 | Windows Store
15 | 10.0
16 | 10.0.18362.0
17 | 10.0.16299.0
18 | example_TemporaryKey.pfx
19 | FE631A250ECAB1AA1F9EFF207E4A076F3C22D958
20 | password
21 |
22 |
23 |
24 | $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'node_modules\react-native-windows\package.json'))\node_modules\react-native-windows\
25 |
26 |
27 |
28 | Debug
29 | ARM
30 |
31 |
32 | Debug
33 | ARM64
34 |
35 |
36 | Debug
37 | Win32
38 |
39 |
40 | Debug
41 | x64
42 |
43 |
44 | Release
45 | ARM
46 |
47 |
48 | Release
49 | ARM64
50 |
51 |
52 | Release
53 | Win32
54 |
55 |
56 | Release
57 | x64
58 |
59 |
60 |
61 | Application
62 | Unicode
63 |
64 |
65 | true
66 | true
67 |
68 |
69 | false
70 | true
71 | false
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | Use
90 | pch.h
91 | $(IntDir)pch.pch
92 | Level4
93 | %(AdditionalOptions) /bigobj
94 | 4453;28204
95 |
96 |
97 |
98 |
99 | _DEBUG;%(PreprocessorDefinitions)
100 |
101 |
102 |
103 |
104 | NDEBUG;%(PreprocessorDefinitions)
105 |
106 |
107 |
108 |
109 | MainPage.xaml
110 | Code
111 |
112 |
113 |
114 |
115 |
116 | App.xaml
117 |
118 |
119 |
120 |
121 | Designer
122 |
123 |
124 |
125 |
126 | Designer
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 | MainPage.xaml
143 | Code
144 |
145 |
146 |
147 |
148 | Create
149 |
150 |
151 | App.xaml
152 |
153 |
154 |
155 |
156 |
157 | App.xaml
158 |
159 |
160 | MainPage.xaml
161 | Code
162 |
163 |
164 |
165 |
166 |
167 |
168 | false
169 |
170 |
171 |
172 |
173 | Designer
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 | This project references targets in your node_modules\react-native-windows folder. The missing file is {0}.
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
197 |
198 |
199 |
200 |
201 |
202 |
--------------------------------------------------------------------------------