Skip to content

Instantly share code, notes, and snippets.

@CrandellWS
Forked from ditzel/Paintable.cs
Last active March 20, 2023 03:41
Show Gist options
  • Save CrandellWS/d791fac4b6cfb03c42d22b737ae70393 to your computer and use it in GitHub Desktop.
Save CrandellWS/d791fac4b6cfb03c42d22b737ae70393 to your computer and use it in GitHub Desktop.
Drawing Canvas
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.InputSystem;
public class SignatureCapture : MonoBehaviour
{
[SerializeField] private GameObject brushPrefab;
[SerializeField] private float brushSize = 0.1f;
[SerializeField] private RenderTexture renderTexture;
private Camera mainCamera;
private InputAction drawAction;
private InputAction touchPositionAction;
// Initialization
private void Awake()
{
mainCamera = Camera.main;
// Set up the new Input System
drawAction = new InputAction("Draw", InputActionType.Value, "<Pointer>/press");
touchPositionAction = new InputAction("Position", InputActionType.Value, "<Pointer>/position");
drawAction.Enable();
touchPositionAction.Enable();
}
private void OnEnable()
{
if (drawAction != null)
{
drawAction.Enable();
}
if (touchPositionAction != null)
{
touchPositionAction.Enable();
}
}
private void OnDisable()
{
if (drawAction != null)
{
drawAction.Disable();
}
if (touchPositionAction != null)
{
touchPositionAction.Disable();
}
}
// Update is called once per frame
private void Update()
{
DrawWithBrush();
}
// Draw with the brush when the left mouse button is pressed or touch input is detected
private void DrawWithBrush()
{
if (drawAction.ReadValue<float>() > 0)
{
Vector2 screenPosition = touchPositionAction.ReadValue<Vector2>();
Ray ray = mainCamera.ScreenPointToRay(screenPosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Instantiate a brush
GameObject brushInstance = Instantiate(brushPrefab, hit.point + Vector3.up * 0.1f, Quaternion.identity, transform);
brushInstance.transform.localScale = Vector3.one * brushSize;
}
}
}
// Save the signature as an image
public void Save()
{
StartCoroutine(SaveCoroutine());
}
private IEnumerator SaveCoroutine()
{
// Wait for rendering
yield return new WaitForEndOfFrame();
string filePath = Path.Combine(Application.dataPath, "savedSignature.png");
Debug.Log($"Saving signature to {filePath}");
// Set active texture
RenderTexture.active = renderTexture;
// Convert RenderTexture to Texture2D
Texture2D texture2D = new Texture2D(renderTexture.width, renderTexture.height);
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
// Write data to file
byte[] imageData = texture2D.EncodeToPNG();
File.WriteAllBytes(filePath, imageData);
// Reset active texture
RenderTexture.active = null;
}
}
@CrandellWS
Copy link
Author

this script at this time is untested but looks usable to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment