Skip to content

Instantly share code, notes, and snippets.

@ditzel
Created April 7, 2018 13:42
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save ditzel/559f77d90b690e840de13823a62a68db to your computer and use it in GitHub Desktop.
Save ditzel/559f77d90b690e840de13823a62a68db to your computer and use it in GitHub Desktop.
Drawing Canvas
using System.Collections;
using System.IO;
using UnityEngine;
public class Paintable : MonoBehaviour {
public GameObject Brush;
public float BrushSize = 0.1f;
public RenderTexture RTexture;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
//cast a ray to the plane
var Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(Ray, out hit))
{
//instanciate a brush
var go = Instantiate(Brush, hit.point + Vector3.up * 0.1f, Quaternion.identity, transform);
go.transform.localScale = Vector3.one * BrushSize;
}
}
}
public void Save()
{
StartCoroutine(CoSave());
}
private IEnumerator CoSave()
{
//wait for rendering
yield return new WaitForEndOfFrame();
Debug.Log(Application.dataPath + "/savedImage.png");
//set active texture
RenderTexture.active = RTexture;
//convert rendering texture to texture2D
var texture2D = new Texture2D(RTexture.width, RTexture.height);
texture2D.ReadPixels(new Rect(0, 0, RTexture.width, RTexture.height), 0, 0);
texture2D.Apply();
//write data to file
var data = texture2D.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/savedImage.png", data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment