Friday, February 15, 2019

React Native Sketch Canvas Android or IOS Example

This tutorial explains how to design sketch and canvas in react native application. This is very helpful for drawing, designing layout and capturing the user signature in android or iOS application with help of react native application. This React Native component for drawing by touching support on both iOS and Android.

React Native Sketch Canvas Android or IOS Example

Lets see the below features of react-native-sketch-canvas.
  1. Support iOS and Android
  2. Stroke thickness and color are changable while drawing.
  3. Can undo strokes one by one.
  4. Can serialize path data to JSON. So it can sync other devices or someone else and continue to edit.
  5. Save drawing to a non-transparent image (png or jpg) or a transparent image (png only)
  6. Use vector concept. So sketches won't be cropped in different sizes of canvas.
  7. Support translucent colors and eraser.
  8. Support drawing on an image (Thanks to diego-caceres-galvan)
  9. High performance 
  10. Can draw multiple canvases in the same screen.
  11. Can draw multiple multiline text on canvas.

Custom Drawing with Canvas : 

Lets see the below example that helps to build more understanding to create a simple drawing canvas in react native application.



Step-1 : Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step-2 : Install the react-native-sketch-canvas package in your React Native project.
npm install @terrylinla/react-native-sketch-canvas --save

Screenshots after successful installation.

Step-3 : Link all native dependencies:
react-native link @terrylinla/react-native-sketch-canvas


NOTE : No additional steps are required for iOS.

Step-4: Open App.js  in your favourite code editor and erase all code and follow this tutorial.

Step-5: Lets place the below lines of code in your App component. Make sure all the mandatory dependencies should present in the App component.

import React, { Component } from 'react';
import {
  Platform, 
  StyleSheet,
  Text,
  View,
  Alert,
} from 'react-native';

import RNSketchCanvas from '@terrylinla/react-native-sketch-canvas';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <RNSketchCanvas
            containerStyle={{ backgroundColor: 'transparent', flex: 1 }}
            canvasStyle={{ backgroundColor: 'transparent', flex: 1 }}
            defaultStrokeIndex={0}
            defaultStrokeWidth={5}
            closeComponent={<View style={styles.functionButton}><Text style={{color: 'white'}}>Close</Text></View>}
            undoComponent={<View style={styles.functionButton}><Text style={{color: 'white'}}>Undo</Text></View>}
            clearComponent={<View style={styles.functionButton}><Text style={{color: 'white'}}>Clear</Text></View>}
            eraseComponent={<View style={styles.functionButton}><Text style={{color: 'white'}}>Eraser</Text></View>}
            strokeComponent={color => (
              <View style={[{ backgroundColor: color }, styles.strokeColorButton]} />
            )}
            strokeSelectedComponent={(color, index, changed) => {
              return (
                <View style={[{ backgroundColor: color, borderWidth: 2 }, styles.strokeColorButton]} />
              )
            }}
            strokeWidthComponent={(w) => {
              return (<View style={styles.strokeWidthButton}>
                <View  style={{
                  backgroundColor: 'white', marginHorizontal: 2.5,
                  width: Math.sqrt(w / 3) * 10, height: Math.sqrt(w / 3) * 10, borderRadius: Math.sqrt(w / 3) * 10 / 2
                }} />
              </View>
            )}}
            saveComponent={<View style={styles.functionButton}><Text style={{color: 'white'}}>Save</Text></View>}
            savePreference={() => {
              return {
                folder: 'RNSketchCanvas',
                filename: String(Math.ceil(Math.random() * 100000000)),
                transparent: false,
                imageType: 'png'
              }
            }}
            //onSketchSaved={(success, filePath) => { alert('filePath: ' + filePath); }}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',

  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  },
  strokeColorButton: {
    marginHorizontal: 2.5, marginVertical: 8, width: 30, height: 30, borderRadius: 15,
  },
  strokeWidthButton: {
    marginHorizontal: 2.5, marginVertical: 8, width: 30, height: 30, borderRadius: 15,
    justifyContent: 'center', alignItems: 'center', backgroundColor: '#39579A'
  },
  functionButton: {
    marginHorizontal: 2.5, marginVertical: 8, height: 30, width: 60,
    backgroundColor: '#39579A', justifyContent: 'center', alignItems: 'center', borderRadius: 5,
  }
});

Step-5: if you like to store or save the canvas in android device, then click on save button. We are using android emulator for this demo and in order to see the file location we need to open device file explorer in android studio.Once you click on save button, it will store the canvas in below location in your android device :
Storage location :  /storage/emulated/0/Pictures/RNSketchCanvas



Screenshots : 

React Native Sketch Canvas Android or IOS Example
React Native Sketch Canvas Android or IOS Example

React Native Sketch Canvas Android or IOS Example

Download Link :
https://github.com/skptricks/React-Native/tree/master/React%20Native%20Sketch%20Canvas%20Android%20Or%20IOS%20Example

This is all about React Native Sketch Canvas Android or IOS Example. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


10 comments:

  1. Hi Sir, I am not able to save the image...How can I do that?

    ReplyDelete
    Replies
    1. You need to use onSketchSaved props in RNSketchCanvas component, in which apply the below line of code.
      onSketchSaved={(success, filePath) => { alert('filePath: ' + filePath); }}

      Delete
  2. Hi. Congratulations and thanks for your tutorials. Thanks to them we can learn things like me.
    My name is Miguel Espeso and I am now starting to create with React Native, so I am a newbie.
    Well, I have the problem described in the previous question. I personally am running the project in an emulator, with the command react-native run-android, but I can not find where the created drawings are saved.
    I do not know what file I must create or modify in order to save the drawings, either in the emulator or in my mobile device, which is where I want to have the application.
    I have a little warning in the emulator that says the following:
    Accessing view manager configs directly off UIManager via UIManager [RNSketchCanvas]
    is no longer supported.
    Use UIManager getViewManagerConfig ('RNSketchCanvas') instead.

    If you could help me with this, what file should I edit or what file should I create, I would be very grateful.
    Even so, I will continue studying the RNSketchCanvas documentation. to try to give more functionality to the application and be able to erase what you draw and write.
    Thank you for your contribution, greetings.

    ReplyDelete
  3. You need to use onSketchSaved props in RNSketchCanvas component, in which apply the below line of code.
    onSketchSaved={(success, filePath) => { alert('filePath: ' + filePath); }}

    and follow the step number 5 of this tutorial.

    ReplyDelete
    Replies
    1. Thanks for your reply.
      I'm not sure if what I should do is change the following line:
      // onSketchSaved = {(success, filePath) => {alert ('filePath:' + filePath); }}

      for this other line:
      onSketchSaved = {(success, filePath) => {alert ('filePath:' + filePath); }}

      Should I just delete the comment or should I add more code? ?
      Thank you.

      Delete
  4. Hi, congratulations for your work.
    I followed the tutorial and can not find a way to change the text size of the buttons.
    Could you help me with this?
    I have changed the value in the following code, but I can not change the size of the text, so the text does not fit on the button and extends in two lines on the buttons and is very ugly.
    How can I reduce the text size of the buttons?
    I'm working on Android
    Thank you
    headerText: {
    fontSize: 5,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
    }

    ReplyDelete
  5. Hi, congratulations for your work.
    I followed the tutorial and can not find a way to change the text size of the buttons.
    Could you help me with this?
    I have changed the value in the following code, but I can not change the size of the text, so the text does not fit on the button and extends in two lines on the buttons and is very ugly.
    How can I reduce the text size of the buttons?
    I'm working on Android
    Thank you
    headerText: {
    fontSize: 5,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
    }

    ReplyDelete
  6. if you want to change button size, color etc. then you need to modify closeComponent, undoComponent, clearComponent, eraseComponent props of your code.

    ReplyDelete
    Replies
    1. Thanks for your support.
      I added 'fontSize: 5' to the function styles: 'functionButton' but the text remains the same, it does not change the size.
      Thanks, I will continue looking for a way to correct this.

      Delete