๐ŸŽจ A React Native Sketch component for touch-based drawing.

Overview

๐ŸŽจ React Native Sketch

npm Downloads MIT License

A React Native component for touch-based drawing.

Capture

Features

  • ๐Ÿ‘† Draw with your finger, and export an image from it.
  • ๐Ÿ– Change the stroke color and thickness on the fly.
  • ๐Ÿ‘ป Generate a transparent image (or not).

Setup

Install the module from npm:

npm i -S react-native-sketch

Link the module to your project:

react-native link react-native-sketch

Usage

import React from 'react';
import { Alert, Button, View } from 'react-native';
import Sketch from 'react-native-sketch';

export default class MyPaint extends React.Component {
  save = () => {
    this.sketch.save().then(({ path }) => {
      Alert.alert('Image saved!', path);
    });
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Sketch
          ref={sketch => {
            this.sketch = sketch;
          }}
          strokeColor="#ff69b4"
          strokeThickness={3}
        />
        <Button onPress={this.save} title="Save" />
      </View>
    );
  }
}

API

Here are the props of the the component:

Name Type Default value Comment
fillColor String null The color of the sketch background. Default to null to keep it transparent! Note: This is different from the style.backgroundColor property, as the former will be seen in your exported drawing image, whereas the latter is only used to style the view.
imageType String png The type of image to export. Can be png or jpg. Default to png to get transparency out of the box.
onChange Function () => {} Callback function triggered after every change on the drawing. The function takes one argument: the actual base64 representation of your drawing.
onClear Function () => {} Callback function triggered after a clear has been triggered.
strokeColor String '#000000' The stroke color you want to draw with.
strokeThickness Number 1 The stroke thickness, in pixels.
style Style object null Some View styles if you need.

The component also has some instance methods:

Name Return type Comment
clear() Promise Clear the drawing. This method is a Promise mostly to be consistent with save(), but you could simply type: this.sketch.clear();
save() Promise Save the drawing to an image, using the defined props as settings (imageType, fillColor, etc...). The Promise resolves with an object containing the path property of that image. Ex: this.sketch.save().then(image => console.log(image.path));

Examples

The project contains a folder examples that contains few demos of how to use react-native-sketch. Just copy and paste the code to your React Native application.

  • Basic: uses the bare minimum to make it work.
  • Digital Touch: tries to reproduce the look and feel of iOS Message Digital Touch.

Feel free to play with them!

Known issues

  • Rotating the screen gets to a weird behavior of the sketch view: #23

Notes

  • If you're using Expo, you will have to detach to ExpoKit, as this module uses native iOS code.
  • The module is available only on iOS for now, as I don't know Android development... But if you think you can help on that matter, please feel free to create a Pull Request!
  • The module uses this smooth freehand drawing technique under the hood.

Contributing

Feel free to contribute by sending a pull request or creating an issue.

License

MIT

Issues
  • Native component for

    Native component for "RNSketch" does not exist

    Im getting this error when I require Sketch and it doesn't seem to be working.

    bug 
    opened by SaintEmbers 17
  • Is it possible to draw on a transparent background?

    Is it possible to draw on a transparent background?

    I am asking as I want to draw over image but do not change the existing image. Thanks

    enhancement 
    opened by aprihodko 12
  • RN 0.40 compatability

    RN 0.40 compatability

    Thanks for the component, it's exactly what I needed for a little project. However, I upgraded to RN 0.40 recently and it doesn't appear to be working. Not sure what the breaking change was, but wanted to let you know the community still appreciates this library! :)

    bug 
    opened by stirman 10
  • Crash if trying to save without touching the canvas?

    Crash if trying to save without touching the canvas?

    So If I call save without drawing anything I get a crash

    default	15:33:58.172747 +0100	paack	Exception '*** -[_NSPlaceholderData initWithBase64EncodedString:options:]: nil string argument' was thrown while invoking saveDrawing on target RNSketchManager with params (
        "<null>",
        png,
        2618,
        2619
    )
    callstack: (
    	0   CoreFoundation                      0x00000001058421ab __exceptionPreprocess + 171
    	1   libobjc.A.dylib                     0x0000000103d3cf41 objc_exception_throw + 48
    	2   CoreFoundation                      0x00000001058b6cb5 +[NSException raise:format:] + 197
    	3   Foundation                          0x00000001037612bb -[NSData(NSData) initWithBase64EncodedString:options:] + 84
    	4   paack                               0x000000010323651a -[RNSketchManager saveDrawing:ofType:resolve:reject:] + 538
    	5   CoreFoundation                      0x00000001057c649c __invoking___ + 140
    	6   CoreFoundation                      0x00000001057c6370 -[NSInvocation invoke] + 320
    	7   CoreFoundation                      0x00000001057ded56 -[NSInvocation invokeWithTarget:] + 54
    	8   pa<โ€ฆ>
    
    

    Thank you ๐Ÿ˜Š

    opened by rborn 9
  • It is not working.

    It is not working.

    I use mouse as input. Can not draw anything on the screen. why?

    opened by ohsei 9
  • Change #import to solve compile error">

    Change #import "RCTXxx.h" to to solve compile error

    I'm using React Native 0.44. There are a couple of compile errors after I added this useful component. The error said Duplicate interface definition for class 'RCTView'. It's the same with other classes like RCTBridge, RCTEventDispatcher, etc.

    I found a solution and it works for me. Just change #import "RCTXxx.h" to #import <React/RCTXxx.h>.

    I'll send a PR later.

    opened by jaybowong 7
  • Update Sketch View From RN

    Update Sketch View From RN

    • Added an image property that can be used by React Native to force an update to the native view with the new function setImage(image) where image is a base64 encoded string.
    • Allowed for transparent background, and switched the default background from blackColor to clearColor.

    Similar to what @stantoncbradley did in response to #6, I wanted to be able to draw on top of an image, and I also wanted to add the ability to undo lines that were drawn. I am working in RN ~0.40, so I opened this up against the react-native-0.40 branch. sketch

    opened by gensc004 6
  • Support RN 0.40 headers while retaining backwards compatibility.

    Support RN 0.40 headers while retaining backwards compatibility.

    Use #if to conditionally import React headers.

    opened by peacechen 4
  • Reset

    Reset

    How exactly do I access onReset? It seems likes its built in to the canvas without a way to trigger it. Thanks!

    enhancement 
    opened by SaintEmbers 4
  • v1.0

    v1.0

    This PR aims to gather few changes to prepare for [email protected]. This is a major bump as few of the changes listed below are breaking changes. In fact, quite a few methods and properties have been renamed, but the API won't change that much anymore, hopefully. ๐Ÿ˜‡

    REMOVED:

    • [x] The clearButtonHidden property and the internal _clearButton view have been removed. This is because the clear method has now to be called from an outside component (that was the goal for a long time!).

    CHANGED:

    • [x] React Native >= 0.40 is now compatible out of the box. This is a breaking change for people using with in an older version of React Native (https://github.com/jgrancher/react-native-sketch/pull/20).
    • [x] The fillColor property has been changed to be null by default, in order to get a transparent background out of the box.
    • [x] The imageType property to export the drawing is now png by default, in the same effort for a transparent background. You can still set it to jpg if you want.
    • [x] The onReset event callback has been renamed to onClear.
    • [x] The saveImage method has been renamed to save AND doesn't require any argument anymore. We keep the state of the drawing in the bridge for you, so that you don't need to keep a reference of the encoded representation of the image on every change. The onChange still exists, and is still returning the base64 representation of the drawing, but you don't have to save it into your component's state in order to pass it to save later on.
    • [x] The two methods clear and save are now Promises, allowing you to type:
    this.sketch.clear().then(() => console.log('Thanks for drawing with us.'));
    this.sketch.save().then(image => console.log(`Here is your drawing image: ${image.path}`));
    
    • [x] Code cleanup (from https://github.com/Thinkmill/react-native-sketch/commit/5bab7f21854aca53e85a9f3d21f98e9aaea3669f).
    • [x] The README.md has been updated with more documentation.

    ADDED:

    • [x] An examples folder has been created.

    Let me know your thoughts! (I'm thinking of you guys who helped me before: @blargity @vccabral @stantoncbradley @gensc004 @alexsotocx)

    opened by jgrancher 4
  • Can you add types for it?

    Can you add types for it?

    Would be sweet, if there were type to have them in Typescript.

    opened by k3rne1pan1c 0
  • Invariant Violation: Native component for

    Invariant Violation: Native component for "RNSketch" does not exist

    Hi! Maybe there is something wrong with my app, since I've tried a few other ways to daw an image / capture a signature and have been getting the same error.

    Here's my system info: Environment: OS: macOS High Sierra 10.13.4 Node: 9.5.0 Yarn: 1.3.2 npm: 5.6.0 Watchman: Not Found Xcode: Xcode 9.3.1 Build version 9E501 Android Studio: 3.1 AI-173.4720617

    Packages: (wanted => installed) react: 16.3.1 => 16.3.1 react-native: ^0.55.4 => 0.55.4

    And full rundown of the error I am getting: Invariant Violation: Native component for "RNSketch" does not exist

    This error is located at: in RNSketch (at index.ios.js:69) in Sketch (at SelectVehicleScreen.js:15) in RCTView (at View.js:60) in View (at SelectVehicleScreen.js:14) in MyPaint (at SceneView.js:10) in SceneView (at StackViewLayout.js:424) in RCTView (at View.js:60) in View (at StackViewLayout.js:423) in RCTView (at View.js:60) in View (at StackViewLayout.js:422) in RCTView (at View.js:60) in View (at createAnimatedComponent.js:154) in AnimatedComponent (at StackViewCard.js:12) in Card (at createPointerEventsContainer.js:28) in Container (at StackViewLayout.js:484) in RCTView (at View.js:60) in View (at StackViewLayout.js:381) in RCTView (at View.js:60) in View (at StackViewLayout.js:380) in StackViewLayout (at withOrientation.js:30) in withOrientation (at StackView.js:61) in RCTView (at View.js:60) in View (at Transitioner.js:146) in Transitioner (at StackView.js:22) in StackView (at createNavigator.js:96) in Navigator (at createKeyboardAwareNavigator.js:11) in KeyboardAwareNavigator (at createNavigationContainer.js:366) in NavigationContainer (at App.js:42) in App (at registerRootComponent.js:35) in RootErrorBoundary (at registerRootComponent.js:34) in ExpoRootComponent (at renderApplication.js:33) in RCTView (at View.js:60) in View (at AppContainer.js:102) in RCTView (at View.js:60) in View (at AppContainer.js:122) in AppContainer (at renderApplication.js:32)

    Not doing any super special:

    1. npm start
    2. "R" to refresh
    3. "a" for my android emulator
    4. Expo starts up and I get the above error.

    I should also note that I am using the example code in its entirety to try to minimize the possibility I am doing something silly ("Usage" @ https://github.com/jgrancher/react-native-sketch).

    Any help is appreciated!

    opened by tmehta2442 4
  • Android implementation

    Android implementation

    I was working on a cross-platform POC with some sketch functionality and I was loving the way this performed in iOS, but was saddened to see that it was lacking an Android implementation. I checked out the closed PRs and it appears there was one in the works, but was closed in favour of another library? It didn't make much sense to me to pull in two libraries for the same problem, so I decided to take a stab at an Android implementation.

    The drawing itself isn't as smooth as the iOS side of things because I haven't implemented the same smooth freehand drawing techniques detailed in the readme. I'm going to look into that this weekend, or perhaps as a follow-up PR (if this gets merged).

    So far I've simply exposed the API and kept it the same as the iOS side of things:

    android

    It's definitely on the larger side due to the nature of the additions but take a look and let me know what you think.

    Thanks! ๐ŸŽˆ

    opened by stefannew 7
  • Is it possible to retrieve the drawing's vector values?

    Is it possible to retrieve the drawing's vector values?

    Hi, this library seems very good, thank's for making it happen ! I was wondering if we could save the drawing as a vector file, or just retrieve the vector values from the drawing, instead of saving the image as png or jpg?

    opened by the-duck 0
  • Multiple instances of Sketch component

    Multiple instances of Sketch component

    Is it possible to have several independent sketch elements? It seems only a single Sketch component is being loaded on the screen.

    To be more specific - this what I'm trying to do:

    Component1 contains a single Sketch component:

    <View>
         <Sketch
              style={styles.notes}
              ref={sketch => {
                this.sketch = sketch;
              }}
              strokeColor="#999999"
              strokeThickness={2}
         />
    </View>
    

    Then, I create several Component1 instances:

    <View>
         <Component1 />
         <Component1 />
         <Component1 />
    </View>
    

    I expect to see 3 independent Sketch components in which user can draw different strokes. However, only a single Sketch component actually being loaded.

    opened by gorork 1
  • Support for an eraser?

    Support for an eraser?

    Are there any plans on adding eraser functionality? If not I'll take a look at contributing :)

    enhancement help wanted 
    opened by zdenham 3
  • Initial Image and/or Custom Image Data Prop

    Initial Image and/or Custom Image Data Prop

    This is a rebuild of my coworker @gensc004's work to allow initial images to the Sketchpad. I have more past experience with ObjC code so I worked on upgrading it to work inline with the change that happened in this library since #27 was opened.

    The implementation I built here is a new prop, imageData that is passed into the native component. Here's what happens:

    1. <Sketch is passed imageData as a prop at first render.
    2. Prop is copied to state of the JS component, and sent to the native component.
    3. (later): Native component calls onChange() when a line is drawn.
    4. JS component updates state and reapplies imageData to the native component <- this causes double rendering of the line...once immediately after the line is drawn, and again once the JS code "accepts" the line.
    5. (opt): At any time, a new imageData value passed to <Sketch will overwrite the current value rendered in native code. If the parent component calls setState() within the onChange() function's callback, the change will be deduplicated by the React reconciler and only the parent component's value will be applied.

    For me, the double rendering resolves an issue where the JS state is out-of-sync with the ObjC state for this component. Ideally, we would only need to render once...but the solution to this could be in a few different ways...I would vote to either leave the double rendering as there's minimal performance impact, or have the end-of-line-drawn not trigger the render, and rely on the JS state for accurate imageData information.

    Remaining Tasks

    • [ ] Discuss & agree on double-rendering ObjC code
    • [ ] Add documentation for the new property
    opened by hnryjms 6
  •  Coordinates

    Coordinates

    How can i get an array of coordinates before saving to images ?

    enhancement help wanted 
    opened by minhnhatspk 3
  • ios-scratch-n-see react-native

    ios-scratch-n-see react-native

    Hi guys, Is there a way to do https://github.com/moqod/ios-scratch-n-see in React Native? Or should I wrap this module and provide a JS bridge to use that lib? or maybe I can use sketch to imitate the same functionality?

    FYI - I'm getting like 30 errors when I try to build sketch into my react-native project after linking it. I tried to run in on RN 0.41.2 and downgraded version of 0.40.0 screen shot 2017-02-08 at 5 17 53 pm

    with 0.41.2 there are 30 Xcode errors with 0.40.0 there are 18 xcode errors

    react-native-cli 2.0.1

    Any help would be appreciated.

    enhancement help wanted question 
    opened by rstormsf 2
  • Changing container size causes bottom half of sketch to be black

    Changing container size causes bottom half of sketch to be black

    Sketch works well initially in both landscape and portrait. However if the container size changes (e.g. display rotation), anything drawn on it is stretched, then when more is drawn on the sketch, the bottom half turns black. This can happen when the container is set to flex:1, even if the Sketch component has fixed width & height.

    help wanted 
    opened by peacechen 1
Owner
Jeremy Grancher
Senior front-end developer at @thinkmill. React and React Native enthusiast. โš›๏ธ
Jeremy Grancher
A React Native component for drawing by touching on both iOS and Android.

react-native-sketch-canvas A React Native component for drawing by touching on both iOS and Android. Features Support iOS and Android Stroke thickness

Terry 568 Jan 2, 2022
Declarative API exposing platform native touch and gesture system to React Native.

React Native Gesture Handler Declarative API exposing platform native touch and gesture system to React Native. React Native Gesture Handler provides

Software Mansion 4.5k Jan 15, 2022
โœ‚๏ธ React-Native component to cut a touch-through holes anywhere you want. Perfect solution for tutorial overlay

How it works code import { RNHoleView } from 'react-native-hole-view'; <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <

ibitcy 131 Jan 19, 2022
react-native-radial-menu โ˜…153 - A Radial Menu optimized for touch interfaces

React Native Radial Menu Installation npm install react-native-radial-menu Usage var RadialMenu = require('react-native-radial-menu'); var Applicatio

Bogdan Silivestru 174 Nov 25, 2021
Custom touch bar or digital macropad app for GNU/Linux ๐Ÿง using an Android device ๐Ÿ“ฑ

Custom touch bar or digital macropad app for GNU/Linux ?? using an Android device ??

Fabiรกn Velosa 3 Dec 14, 2021
A QR Code generator for React Native based on react-native-svg and node-qrcode.

react-native-qrcode-svg A QR Code generator for React Native based on react-native-svg and javascript-qrcode. Discussion: https://discord.gg/RvFM97v F

JerryShen 803 Jan 14, 2022
Based on pure JS scripts, without relying on native, no need for react-native link, Title / Header / Tabs / Sticky / Screen components can be flexibly configured, among which Tabs / Sticky can slide When it reaches the top, it will be topped.

react-native-scrollable-tabview English | ็ฎ€ไฝ“ไธญๆ–‡ Based on pure JS scripts, without relying on native, no need for react-native link,Title / Header / Tab

null 117 Jan 10, 2022
โš› Cross-platform React Native dialogs based on the Modal component

React Native Simple Dialogs โš› Cross-platform React Native dialogs based on the Modal component. Features Custom Dialog Confirm Dialog Progress Dialog

Douglas Nassif Roma Junior 234 Dec 28, 2021
react native Picker component for both Android and iOS based on pure JavaScript [for the old realize, you can use the version 0.0.8]

The React-Native-Picker react native Picker component for both Android and iOS based on pure JavaScript. Main For the iOS, using PickerIOS as the basi

X  Fruit Team 78 Aug 3, 2021
React Native Slider component with two markers based on NMRangeSlider.

Native iOS multi slider component for React Native Native iOS multi slider component for React Native with two markers based on NMRangeSlider. react-n

Enrise 34 Jul 3, 2021
React Native component that implements the OAuth2 flow for the Appwrite BaaS. It's based on a Modal implementation

react-native-appwrite-oauth React Native component that implements the OAuth2 flow for the Appwrite BaaS (Backend-as-a-Service). It's based in a Modal

Diego BM 8 Jan 7, 2022
:boom: React Native UI Library based on Eva Design System :new_moon_with_face::sparkles:Dark Mode

UI Kitten Documentation UI Kitten is a React Native UI Library that allows you creating stunning multi-brand cross-platform mobile applications. The l

Akveo 8.9k Jan 15, 2022
Android and iOS charts based on react-native-svg and paths-js

** Capital One built this project to help our engineers as well as users in the react native community. We have decided to focus on alternatives to re

Capital One 885 Dec 28, 2021
ํ•™๊ต ์™ธ๋ฐ•์‹ ์ฒญ ์ž๋™ํ™” App Based in React Native

?? Auto_Overnight ํ•™๊ต ์™ธ๋ฐ•์‹ ์ฒญ ์ž๋™ํ™” App Based in React Native with Expo ํ•™๊ต ์™ธ๋ฐ• ์‹ ์ฒญ ๋กœ์ง์„ ๋‹จ์ˆœํ™” ํ•˜๊ณ  ๋‹ฌ๋ ฅ ํ˜•์‹์œผ๋กœ ๊ฐ„ํŽธํ•˜๊ฒŒ ์‹ ์ฒญ ?? Tech Stack ๋ถ„๋ฅ˜ ๊ธฐ์ˆ  Frontend Backend Etc โš™๏ธ Syst

null 13 Jan 10, 2022
keyboard-aware-view is a react-native package that handles the view position based on input position and keyboard so that the text input doesn't get hidden behind the keyboard.

keyboard-aware-view is a react-native package that handles the view position based on input position and keyboard so that the text input doesn't get hidden behind the keyboard.

Abhiram K 23 Dec 16, 2021
React-native-customizable-toast: yet another toast library based on reanimated 2 layout animations

react-native-customizable-toast yet another toast library based on reanimated 2 layout animations Features Imperative API Fully Customizable Custom to

kubilay 77 Jan 14, 2022
react-native-app-intro is a react native component implementing a parallax effect welcome page using base on react-native-swiper , similar to the one found in Google's app like Sheet, Drive, Docs...

react-native-app-intro react-native-app-intro is a react native component implementing a parallax effect welcome page using base on react-native-swipe

FuYaoDe 3.2k Jan 17, 2022
react-native-swiper2 โ˜…86 - Swiper component for React Native. Supersede react-native-swiper

react-native-swiper2 react-native-swiper is now active again, so swiper2 will stop maintaining. Changelogs [v2.0.7] correct onPageChange index. https:

Sunny Luo 85 Aug 30, 2021
react-native-app-intro is a react native component implementing a parallax effect welcome page using base on react-native-swiper , similar to the one found in Google's app like Sheet, Drive, Docs...

react-native-app-intro react-native-app-intro is a react native component implementing a parallax effect welcome page using base on react-native-swipe

Shinix 61 Nov 13, 2021