ペイントツールみたいなものを作ってみようと思い、今回はマウスで線が描ける所まで試しに作ってみました!
環境
Unity2018.3.0f2
Xcode10.1
実装
Texture2Dを生成し、そのテクスチャに指定した色を設定すればそれっぽくなるのでは?という事で指定する座標はマウス座標をそのまま使いたかったので、UGUIのRawImageを全画面表示する形にしてみました!

スクリプトはこんな感じに!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Paint : MonoBehaviour { [SerializeField] private RawImage m_image = null; private Texture2D m_texture = null; void Start () { var rect = m_image.gameObject.GetComponent<RectTransform>().rect; m_texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false); m_image.texture = m_texture; } void OnDestroy () { if ( m_texture != null ) { Destroy( m_texture ); m_texture = null; } } void Update () { if ( Input.GetMouseButton( 0 ) ) { var pos = Input.mousePosition; m_texture.SetPixel( (int)pos.x, (int)pos.y, Color.red ); m_texture.Apply(); } } } |
実行してみたものがこちらです。
点がまばらで想定したものと全然違いました・・・。塗りつぶす領域を広くしてみればいいのかな?という事で、幅と高さを設定できる形にしてみたものがこちら!
さっきより塗りつぶす領域が広くなった分、見えやすくなりましたが、線のような感じにはなっていません・・・。点と点を繋ぐ形で塗りつぶせばそれっぽくなるだろう!という事で、マウス座標を保存しておき、塗りつぶす領域を前回のマウス座標から今回のマウス座標までを塗っていく形にしてみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Paint : MonoBehaviour { [SerializeField] private RawImage m_image = null; [SerializeField] private int m_width = 4; [SerializeField] private int m_height = 4; private Vector3 m_prevMousePos; private Texture2D m_texture = null; private void Start () { var rect = m_image.gameObject.GetComponent<RectTransform>().rect; m_texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false); m_image.texture = m_texture; } private void OnDestroy () { if ( m_texture != null ) { Destroy( m_texture ); m_texture = null; } } private void Update () { if ( Input.GetMouseButton( 0 ) ) { int width = m_width; int height = m_height; var dir = m_prevMousePos - Input.mousePosition; var dist = (int)dir.magnitude; dir = dir.normalized; for ( int d = 0; d < dist; ++d ) { var pos = Input.mousePosition + dir * d; pos.x -= width/2.0f; pos.y -= height/2.0f; for ( int h = 0; h < height; ++h ) { int y = (int)(pos.y + h); if ( y < 0 || y > m_texture.height ) { continue; } for ( int w = 0; w < width; ++w ) { int x = (int)(pos.x + w); if ( x >= 0 && x <= m_texture.width ) { m_texture.SetPixel( x, y, Color.red ); } } } } m_texture.Apply(); } m_prevMousePos = Input.mousePosition; } } |
今度は、思っていた通りになりました!!
まとめ
実際にやってみると、想定と違った結果になったりもしましたが、最終的には線を描く事ができて、自分でやってみる事の大切に改めてきづけました!今回は指定した色を塗っていく形でしたが、テクスチャを元に色を塗っていく形にすればペイントツールのブラシ機能みたいなものも作れるかなと思うので、別の機会にチャレンジしてみたいと思います。