回答編集履歴

1

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

2020/01/15 17:05

投稿

Bongo
Bongo

スコア10807

test CHANGED
@@ -181,3 +181,559 @@
181
181
 
182
182
 
183
183
  すみませんがすぐに試せるモバイル環境を持っていないため、実機上だとどうなるか未確認です。意図と異なる動きをするようでしたら、異常の様子を詳しくコメントいただければ可能であれば直してみようと思います。
184
+
185
+
186
+
187
+ **追記**
188
+
189
+ 「[UNITY LineRendererで線を描く事はできるのですが,canvasの下のimageに描く事は出来ないでしょうか?](https://teratail.com/questions/232888)」の時の`Painter`と折衷させたバージョン
190
+
191
+
192
+
193
+ ```C#
194
+
195
+ using System;
196
+
197
+ using System.Collections.Generic;
198
+
199
+ using UnityEngine;
200
+
201
+ using UnityEngine.EventSystems;
202
+
203
+ using UnityEngine.SceneManagement;
204
+
205
+ using UnityEngine.UI;
206
+
207
+
208
+
209
+ /// <summary>
210
+
211
+ /// お絵描き
212
+
213
+ /// </summary>
214
+
215
+ [RequireComponent(typeof(RectTransform), typeof(Image))]
216
+
217
+ public class Painter : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
218
+
219
+ {
220
+
221
+ // ペンの半径...0で1ピクセルの線になる
222
+
223
+ [Range(0, 5)] public int penRadius;
224
+
225
+
226
+
227
+ // 前景色(ペンの色)
228
+
229
+ public Color foregroundColor = Color.red;
230
+
231
+
232
+
233
+ // 背景色
234
+
235
+ // ただし、現状は以前のご質問で製作した「元々セットされているテクスチャを下絵にする」
236
+
237
+ // という方式になっているため、この背景色はスクリプト中で使用されていない
238
+
239
+ [SerializeField] private Color backgroundColor = Color.white;
240
+
241
+
242
+
243
+ private RectTransform rectTransform;
244
+
245
+ private Image image;
246
+
247
+ private Texture2D texture;
248
+
249
+ private Vector2Int textureSize;
250
+
251
+ private Vector2Int previousPixelPosition;
252
+
253
+ private Vector2Int cachedPixelPosition;
254
+
255
+
256
+
257
+ // 線引き中であることを示すフラグ
258
+
259
+ private bool isPainting;
260
+
261
+
262
+
263
+ private readonly Stack<Texture2D> undoStack = new Stack<Texture2D>();
264
+
265
+ private readonly Stack<Texture2D> redoStack = new Stack<Texture2D>();
266
+
267
+
268
+
269
+ public bool CanUndo => this.undoStack.Count > 0;
270
+
271
+ public bool CanRedo => this.redoStack.Count > 0;
272
+
273
+
274
+
275
+ // タイトルシーンに移動するメソッド
276
+
277
+ // ボタンのインスペクターの「On Click ()」でこのメソッドを実行するよう設定しておく
278
+
279
+ // 個人的な好みでは、「タイトルシーンに移動する」という機能は「Image上にお絵かきする」という機能と
280
+
281
+ // 直接的な関係があるようには感じられないので、別のスクリプトに役割分担させた方がいい気もしますが...
282
+
283
+ public void OnButtonClick()
284
+
285
+ {
286
+
287
+ SceneManager.LoadScene("Title");
288
+
289
+ }
290
+
291
+
292
+
293
+ public void OnPointerDown(PointerEventData eventData)
294
+
295
+ {
296
+
297
+ this.isPainting = true;
298
+
299
+ }
300
+
301
+
302
+
303
+ public void OnPointerUp(PointerEventData eventData)
304
+
305
+ {
306
+
307
+ this.isPainting = false;
308
+
309
+ }
310
+
311
+
312
+
313
+ public void Undo()
314
+
315
+ {
316
+
317
+ if (!this.CanUndo)
318
+
319
+ {
320
+
321
+ return;
322
+
323
+ }
324
+
325
+
326
+
327
+ var previousTexture = this.texture;
328
+
329
+ var poppedTexture = this.undoStack.Pop();
330
+
331
+ this.texture = poppedTexture;
332
+
333
+ this.redoStack.Push(previousTexture);
334
+
335
+ this.UpdateSprite();
336
+
337
+ Debug.Log($"Undo! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
338
+
339
+ }
340
+
341
+
342
+
343
+ public void Redo()
344
+
345
+ {
346
+
347
+ if (!this.CanRedo)
348
+
349
+ {
350
+
351
+ return;
352
+
353
+ }
354
+
355
+
356
+
357
+ var previousTexture = this.texture;
358
+
359
+ var poppedTexture = this.redoStack.Pop();
360
+
361
+ this.texture = poppedTexture;
362
+
363
+ this.undoStack.Push(previousTexture);
364
+
365
+ this.UpdateSprite();
366
+
367
+ Debug.Log($"Redo! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
368
+
369
+ }
370
+
371
+
372
+
373
+ private void Record()
374
+
375
+ {
376
+
377
+ this.undoStack.Push(Instantiate(this.texture));
378
+
379
+ foreach (var textureInRedoStack in this.redoStack)
380
+
381
+ {
382
+
383
+ Destroy(textureInRedoStack);
384
+
385
+ }
386
+
387
+
388
+
389
+ this.redoStack.Clear();
390
+
391
+ Debug.Log($"Record! UndoStack : {this.undoStack.Count} RedoStack : {this.redoStack.Count}");
392
+
393
+ }
394
+
395
+
396
+
397
+ private void UpdateSprite()
398
+
399
+ {
400
+
401
+ var previousSprite = this.image.sprite;
402
+
403
+ this.image.sprite = Sprite.Create(
404
+
405
+ this.texture,
406
+
407
+ new Rect(0, 0, this.texture.width, this.texture.height),
408
+
409
+ Vector2.zero);
410
+
411
+ Destroy(previousSprite);
412
+
413
+ }
414
+
415
+
416
+
417
+ private Vector2Int GetPixelPosition()
418
+
419
+ {
420
+
421
+ if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(
422
+
423
+ this.rectTransform,
424
+
425
+ Input.mousePosition,
426
+
427
+ null,
428
+
429
+ out var pixelPositionFloat))
430
+
431
+ {
432
+
433
+ return this.cachedPixelPosition;
434
+
435
+ }
436
+
437
+
438
+
439
+ var sizeDelta = this.rectTransform.sizeDelta;
440
+
441
+ pixelPositionFloat += sizeDelta * this.rectTransform.pivot;
442
+
443
+ var pixelPosition = new Vector2Int(
444
+
445
+ Mathf.Clamp((int)pixelPositionFloat.x, 0, this.textureSize.x - 1),
446
+
447
+ Mathf.Clamp((int)pixelPositionFloat.y, 0, this.textureSize.y - 1));
448
+
449
+ Debug.Log($"Pixel Position: {pixelPosition}");
450
+
451
+ this.cachedPixelPosition = pixelPosition;
452
+
453
+ return this.cachedPixelPosition;
454
+
455
+ }
456
+
457
+
458
+
459
+ private bool PositionIsWithinTexture(Vector2Int position)
460
+
461
+ {
462
+
463
+ return (position.x >= 0) && (position.y >= 0) &&
464
+
465
+ (position.x < this.textureSize.x) && (position.y < this.textureSize.y);
466
+
467
+ }
468
+
469
+
470
+
471
+ private void PaintAt(Vector2Int position, Color32 color, int radius)
472
+
473
+ {
474
+
475
+ var sqrRadius = radius * radius;
476
+
477
+ for (var i = -radius; i <= radius; i++)
478
+
479
+ {
480
+
481
+ for (var j = -radius; j <= radius; j++)
482
+
483
+ {
484
+
485
+ var p = new Vector2Int(position.x + i, position.y + j);
486
+
487
+ var dot = (i * i) + (j * j);
488
+
489
+ if ((dot <= sqrRadius) && this.PositionIsWithinTexture(p))
490
+
491
+ {
492
+
493
+ this.texture.SetPixel(p.x, p.y, color);
494
+
495
+ }
496
+
497
+ }
498
+
499
+ }
500
+
501
+
502
+
503
+ this.texture.Apply();
504
+
505
+ }
506
+
507
+
508
+
509
+ private void LineTo(Vector2Int from, Vector2Int to, Color32 color, int radius)
510
+
511
+ {
512
+
513
+ var penPosition = from;
514
+
515
+ var x = (float)penPosition.x;
516
+
517
+ var y = (float)penPosition.y;
518
+
519
+ var fromTo = to - from;
520
+
521
+ var fromToSign = new Vector2Int((int)Mathf.Sign(fromTo.x), (int)Mathf.Sign(fromTo.y));
522
+
523
+ var fromToXIsZero = fromToSign.x == 0;
524
+
525
+ var fromToYIsZero = fromToSign.y == 0;
526
+
527
+ fromToSign.x = fromToXIsZero ? 1 : fromToSign.x;
528
+
529
+ fromToSign.y = fromToYIsZero ? 1 : fromToSign.y;
530
+
531
+ var absFromTo = fromToSign * fromTo;
532
+
533
+ var dominantDirection = 0;
534
+
535
+ var delta = Vector2.zero;
536
+
537
+ if (absFromTo.x >= absFromTo.y)
538
+
539
+ {
540
+
541
+ var tangent = fromToXIsZero ? 0 : (float)fromTo.y / fromTo.x;
542
+
543
+ delta.x = fromToSign.x;
544
+
545
+ delta.y = tangent * delta.x;
546
+
547
+ }
548
+
549
+ else
550
+
551
+ {
552
+
553
+ var tangent = fromToYIsZero ? 0 : (float)fromTo.x / fromTo.y;
554
+
555
+ delta.y = fromToSign.y;
556
+
557
+ delta.x = tangent * delta.y;
558
+
559
+ dominantDirection = 1;
560
+
561
+ }
562
+
563
+
564
+
565
+ while (this.PositionIsWithinTexture(penPosition))
566
+
567
+ {
568
+
569
+ try
570
+
571
+ {
572
+
573
+ this.PaintAt(penPosition, color, radius);
574
+
575
+ x += delta.x;
576
+
577
+ y += delta.y;
578
+
579
+ penPosition.x = (int)x;
580
+
581
+ penPosition.y = (int)y;
582
+
583
+ if (fromToSign[dominantDirection] > 0)
584
+
585
+ {
586
+
587
+ if (penPosition[dominantDirection] >= to[dominantDirection])
588
+
589
+ {
590
+
591
+ break;
592
+
593
+ }
594
+
595
+ }
596
+
597
+ else
598
+
599
+ {
600
+
601
+ if (penPosition[dominantDirection] <= to[dominantDirection])
602
+
603
+ {
604
+
605
+ break;
606
+
607
+ }
608
+
609
+ }
610
+
611
+ }
612
+
613
+ catch (Exception e)
614
+
615
+ {
616
+
617
+ Debug.LogException(e);
618
+
619
+ break;
620
+
621
+ }
622
+
623
+ }
624
+
625
+ }
626
+
627
+
628
+
629
+ private void Start()
630
+
631
+ {
632
+
633
+ this.rectTransform = this.transform as RectTransform;
634
+
635
+ this.image = this.GetComponent<Image>();
636
+
637
+ var sizeDelta = this.rectTransform.sizeDelta;
638
+
639
+ var width = (int)sizeDelta.x;
640
+
641
+ var height = (int)sizeDelta.y;
642
+
643
+ var backgroundPixels = (this.image.mainTexture as Texture2D).GetPixels32();
644
+
645
+ this.image.sprite = null;
646
+
647
+ this.texture = new Texture2D(width, height, TextureFormat.ARGB32, false) {filterMode = FilterMode.Bilinear};
648
+
649
+ this.texture.SetPixels32(backgroundPixels);
650
+
651
+ this.texture.Apply();
652
+
653
+ this.textureSize = new Vector2Int(width, height);
654
+
655
+ this.UpdateSprite();
656
+
657
+ }
658
+
659
+
660
+
661
+ private void Update()
662
+
663
+ {
664
+
665
+ if (Input.GetKeyDown(KeyCode.U))
666
+
667
+ {
668
+
669
+ this.Undo();
670
+
671
+ }
672
+
673
+
674
+
675
+ if (Input.GetKeyDown(KeyCode.R))
676
+
677
+ {
678
+
679
+ this.Redo();
680
+
681
+ }
682
+
683
+
684
+
685
+ // 線引き中かどうかに関係なく動作させたいコードはここよりも上に記述する
686
+
687
+ if (!this.isPainting)
688
+
689
+ {
690
+
691
+ // 線引き中に動作されると困るコードがあればこの辺に記述する
692
+
693
+ return;
694
+
695
+ }
696
+
697
+ // 線引き中のみ動作させたいコードはここよりも下に記述する
698
+
699
+
700
+
701
+ if (Input.GetMouseButtonDown(0))
702
+
703
+ {
704
+
705
+ this.Record();
706
+
707
+ this.previousPixelPosition = this.GetPixelPosition();
708
+
709
+ }
710
+
711
+ else if (Input.GetMouseButton(0))
712
+
713
+ {
714
+
715
+ var currentPixelPosition = this.GetPixelPosition();
716
+
717
+ this.LineTo(this.previousPixelPosition, currentPixelPosition, this.foregroundColor, this.penRadius);
718
+
719
+ this.previousPixelPosition = currentPixelPosition;
720
+
721
+ }
722
+
723
+
724
+
725
+ // 右クリックによるUndo
726
+
727
+ if (Input.GetMouseButtonDown(1))
728
+
729
+ {
730
+
731
+ this.Undo();
732
+
733
+ }
734
+
735
+ }
736
+
737
+ }
738
+
739
+ ```