teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

Painterのコードを省略なしで追記

2020/01/15 17:05

投稿

Bongo
Bongo

スコア10816

answer CHANGED
@@ -89,4 +89,282 @@
89
89
  }
90
90
  ```
91
91
 
92
- すみませんがすぐに試せるモバイル環境を持っていないため、実機上だとどうなるか未確認です。意図と異なる動きをするようでしたら、異常の様子を詳しくコメントいただければ可能であれば直してみようと思います。
92
+ すみませんがすぐに試せるモバイル環境を持っていないため、実機上だとどうなるか未確認です。意図と異なる動きをするようでしたら、異常の様子を詳しくコメントいただければ可能であれば直してみようと思います。
93
+
94
+ **追記**
95
+ 「[UNITY LineRendererで線を描く事はできるのですが,canvasの下のimageに描く事は出来ないでしょうか?](https://teratail.com/questions/232888)」の時の`Painter`と折衷させたバージョン
96
+
97
+ ```C#
98
+ using System;
99
+ using System.Collections.Generic;
100
+ using UnityEngine;
101
+ using UnityEngine.EventSystems;
102
+ using UnityEngine.SceneManagement;
103
+ using UnityEngine.UI;
104
+
105
+ /// <summary>
106
+ /// お絵描き
107
+ /// </summary>
108
+ [RequireComponent(typeof(RectTransform), typeof(Image))]
109
+ public class Painter : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
110
+ {
111
+ // ペンの半径...0で1ピクセルの線になる
112
+ [Range(0, 5)] public int penRadius;
113
+
114
+ // 前景色(ペンの色)
115
+ public Color foregroundColor = Color.red;
116
+
117
+ // 背景色
118
+ // ただし、現状は以前のご質問で製作した「元々セットされているテクスチャを下絵にする」
119
+ // という方式になっているため、この背景色はスクリプト中で使用されていない
120
+ [SerializeField] private Color backgroundColor = Color.white;
121
+
122
+ private RectTransform rectTransform;
123
+ private Image image;
124
+ private Texture2D texture;
125
+ private Vector2Int textureSize;
126
+ private Vector2Int previousPixelPosition;
127
+ private Vector2Int cachedPixelPosition;
128
+
129
+ // 線引き中であることを示すフラグ
130
+ private bool isPainting;
131
+
132
+ private readonly Stack<Texture2D> undoStack = new Stack<Texture2D>();
133
+ private readonly Stack<Texture2D> redoStack = new Stack<Texture2D>();
134
+
135
+ public bool CanUndo => this.undoStack.Count > 0;
136
+ public bool CanRedo => this.redoStack.Count > 0;
137
+
138
+ // タイトルシーンに移動するメソッド
139
+ // ボタンのインスペクターの「On Click ()」でこのメソッドを実行するよう設定しておく
140
+ // 個人的な好みでは、「タイトルシーンに移動する」という機能は「Image上にお絵かきする」という機能と
141
+ // 直接的な関係があるようには感じられないので、別のスクリプトに役割分担させた方がいい気もしますが...
142
+ public void OnButtonClick()
143
+ {
144
+ SceneManager.LoadScene("Title");
145
+ }
146
+
147
+ public void OnPointerDown(PointerEventData eventData)
148
+ {
149
+ this.isPainting = true;
150
+ }
151
+
152
+ public void OnPointerUp(PointerEventData eventData)
153
+ {
154
+ this.isPainting = false;
155
+ }
156
+
157
+ public void Undo()
158
+ {
159
+ if (!this.CanUndo)
160
+ {
161
+ return;
162
+ }
163
+
164
+ var previousTexture = this.texture;
165
+ var poppedTexture = this.undoStack.Pop();
166
+ this.texture = poppedTexture;
167
+ this.redoStack.Push(previousTexture);
168
+ this.UpdateSprite();
169
+ Debug.Log($"Undo! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
170
+ }
171
+
172
+ public void Redo()
173
+ {
174
+ if (!this.CanRedo)
175
+ {
176
+ return;
177
+ }
178
+
179
+ var previousTexture = this.texture;
180
+ var poppedTexture = this.redoStack.Pop();
181
+ this.texture = poppedTexture;
182
+ this.undoStack.Push(previousTexture);
183
+ this.UpdateSprite();
184
+ Debug.Log($"Redo! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
185
+ }
186
+
187
+ private void Record()
188
+ {
189
+ this.undoStack.Push(Instantiate(this.texture));
190
+ foreach (var textureInRedoStack in this.redoStack)
191
+ {
192
+ Destroy(textureInRedoStack);
193
+ }
194
+
195
+ this.redoStack.Clear();
196
+ Debug.Log($"Record! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
197
+ }
198
+
199
+ private void UpdateSprite()
200
+ {
201
+ var previousSprite = this.image.sprite;
202
+ this.image.sprite = Sprite.Create(
203
+ this.texture,
204
+ new Rect(0, 0, this.texture.width, this.texture.height),
205
+ Vector2.zero);
206
+ Destroy(previousSprite);
207
+ }
208
+
209
+ private Vector2Int GetPixelPosition()
210
+ {
211
+ if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(
212
+ this.rectTransform,
213
+ Input.mousePosition,
214
+ null,
215
+ out var pixelPositionFloat))
216
+ {
217
+ return this.cachedPixelPosition;
218
+ }
219
+
220
+ var sizeDelta = this.rectTransform.sizeDelta;
221
+ pixelPositionFloat += sizeDelta * this.rectTransform.pivot;
222
+ var pixelPosition = new Vector2Int(
223
+ Mathf.Clamp((int)pixelPositionFloat.x, 0, this.textureSize.x - 1),
224
+ Mathf.Clamp((int)pixelPositionFloat.y, 0, this.textureSize.y - 1));
225
+ Debug.Log($"Pixel Position: {pixelPosition}");
226
+ this.cachedPixelPosition = pixelPosition;
227
+ return this.cachedPixelPosition;
228
+ }
229
+
230
+ private bool PositionIsWithinTexture(Vector2Int position)
231
+ {
232
+ return (position.x >= 0) && (position.y >= 0) &&
233
+ (position.x < this.textureSize.x) && (position.y < this.textureSize.y);
234
+ }
235
+
236
+ private void PaintAt(Vector2Int position, Color32 color, int radius)
237
+ {
238
+ var sqrRadius = radius * radius;
239
+ for (var i = -radius; i <= radius; i++)
240
+ {
241
+ for (var j = -radius; j <= radius; j++)
242
+ {
243
+ var p = new Vector2Int(position.x + i, position.y + j);
244
+ var dot = (i * i) + (j * j);
245
+ if ((dot <= sqrRadius) && this.PositionIsWithinTexture(p))
246
+ {
247
+ this.texture.SetPixel(p.x, p.y, color);
248
+ }
249
+ }
250
+ }
251
+
252
+ this.texture.Apply();
253
+ }
254
+
255
+ private void LineTo(Vector2Int from, Vector2Int to, Color32 color, int radius)
256
+ {
257
+ var penPosition = from;
258
+ var x = (float)penPosition.x;
259
+ var y = (float)penPosition.y;
260
+ var fromTo = to - from;
261
+ var fromToSign = new Vector2Int((int)Mathf.Sign(fromTo.x), (int)Mathf.Sign(fromTo.y));
262
+ var fromToXIsZero = fromToSign.x == 0;
263
+ var fromToYIsZero = fromToSign.y == 0;
264
+ fromToSign.x = fromToXIsZero ? 1 : fromToSign.x;
265
+ fromToSign.y = fromToYIsZero ? 1 : fromToSign.y;
266
+ var absFromTo = fromToSign * fromTo;
267
+ var dominantDirection = 0;
268
+ var delta = Vector2.zero;
269
+ if (absFromTo.x >= absFromTo.y)
270
+ {
271
+ var tangent = fromToXIsZero ? 0 : (float)fromTo.y / fromTo.x;
272
+ delta.x = fromToSign.x;
273
+ delta.y = tangent * delta.x;
274
+ }
275
+ else
276
+ {
277
+ var tangent = fromToYIsZero ? 0 : (float)fromTo.x / fromTo.y;
278
+ delta.y = fromToSign.y;
279
+ delta.x = tangent * delta.y;
280
+ dominantDirection = 1;
281
+ }
282
+
283
+ while (this.PositionIsWithinTexture(penPosition))
284
+ {
285
+ try
286
+ {
287
+ this.PaintAt(penPosition, color, radius);
288
+ x += delta.x;
289
+ y += delta.y;
290
+ penPosition.x = (int)x;
291
+ penPosition.y = (int)y;
292
+ if (fromToSign[dominantDirection] > 0)
293
+ {
294
+ if (penPosition[dominantDirection] >= to[dominantDirection])
295
+ {
296
+ break;
297
+ }
298
+ }
299
+ else
300
+ {
301
+ if (penPosition[dominantDirection] <= to[dominantDirection])
302
+ {
303
+ break;
304
+ }
305
+ }
306
+ }
307
+ catch (Exception e)
308
+ {
309
+ Debug.LogException(e);
310
+ break;
311
+ }
312
+ }
313
+ }
314
+
315
+ private void Start()
316
+ {
317
+ this.rectTransform = this.transform as RectTransform;
318
+ this.image = this.GetComponent<Image>();
319
+ var sizeDelta = this.rectTransform.sizeDelta;
320
+ var width = (int)sizeDelta.x;
321
+ var height = (int)sizeDelta.y;
322
+ var backgroundPixels = (this.image.mainTexture as Texture2D).GetPixels32();
323
+ this.image.sprite = null;
324
+ this.texture = new Texture2D(width, height, TextureFormat.ARGB32, false) {filterMode = FilterMode.Bilinear};
325
+ this.texture.SetPixels32(backgroundPixels);
326
+ this.texture.Apply();
327
+ this.textureSize = new Vector2Int(width, height);
328
+ this.UpdateSprite();
329
+ }
330
+
331
+ private void Update()
332
+ {
333
+ if (Input.GetKeyDown(KeyCode.U))
334
+ {
335
+ this.Undo();
336
+ }
337
+
338
+ if (Input.GetKeyDown(KeyCode.R))
339
+ {
340
+ this.Redo();
341
+ }
342
+
343
+ // 線引き中かどうかに関係なく動作させたいコードはここよりも上に記述する
344
+ if (!this.isPainting)
345
+ {
346
+ // 線引き中に動作されると困るコードがあればこの辺に記述する
347
+ return;
348
+ }
349
+ // 線引き中のみ動作させたいコードはここよりも下に記述する
350
+
351
+ if (Input.GetMouseButtonDown(0))
352
+ {
353
+ this.Record();
354
+ this.previousPixelPosition = this.GetPixelPosition();
355
+ }
356
+ else if (Input.GetMouseButton(0))
357
+ {
358
+ var currentPixelPosition = this.GetPixelPosition();
359
+ this.LineTo(this.previousPixelPosition, currentPixelPosition, this.foregroundColor, this.penRadius);
360
+ this.previousPixelPosition = currentPixelPosition;
361
+ }
362
+
363
+ // 右クリックによるUndo
364
+ if (Input.GetMouseButtonDown(1))
365
+ {
366
+ this.Undo();
367
+ }
368
+ }
369
+ }
370
+ ```