Advertisement
Guest User

Outline Generator

a guest
Jan 19th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. public Sprite GenerateOutline(Sprite sprite)
  2.     {
  3.         Vector2Int originSize = new Vector2Int((int)sprite.rect.width, (int)sprite.rect.height);
  4.         Vector2Int originPivot = new Vector2Int((int)sprite.rect.x, (int)sprite.rect.y);
  5.         Texture2D origin = sprite.texture;
  6.         Vector2Int outlineSize = (originSize + Vector2Int.one) * 2;
  7.         Texture2D outline = new Texture2D(outlineSize.x, outlineSize.y)
  8.         {
  9.             filterMode = FilterMode.Point
  10.         };
  11.         Color[] colors = outline.GetPixels();
  12.         for (int i = 0; i < colors.Length; i++)
  13.         {
  14.             colors[i] = Color.clear;
  15.         }
  16.         outline.SetPixels(colors);
  17.         for (int x = 0; x < originSize.x; x++)
  18.         {
  19.             for (int y = 0; y < originSize.y; y++)
  20.             {
  21.                 Color color = origin.GetPixel(originPivot.x + x, originPivot.y + y);
  22.                 for (int cX = 0; cX < 2; cX++)
  23.                 {
  24.                     for (int cY = 0; cY < 2; cY++)
  25.                     {
  26.                         outline.SetPixel(x * 2 + cX + 1, y * 2 + cY + 1, color);
  27.                     }
  28.                 }
  29.             }
  30.         }
  31.         colors = outline.GetPixels();
  32.         Vector2Int[] neighbours = new Vector2Int[] { Vector2Int.up, Vector2Int.right, Vector2Int.down, Vector2Int.left };
  33.         for (int x = 1; x < outlineSize.x - 1; x++)
  34.         {
  35.             for (int y = 1; y < outlineSize.y - 1; y++)
  36.             {
  37.                 if (colors[x + y * outlineSize.y].a != 0f)
  38.                 {
  39.                     for (int n = 0; n < 4; n++)
  40.                     {
  41.                         Vector2Int position = new Vector2Int(x, y) + neighbours[n];
  42.                         if (colors[position.x + position.y * outlineSize.y].a == 0f)
  43.                         {
  44.                             outline.SetPixel(position.x, position.y, Color.black);
  45.                         }
  46.                     }
  47.                 }
  48.             }
  49.         }
  50.         outline.Apply();
  51.         return Sprite.Create(outline, new Rect(0f, 0f, outlineSize.x, outlineSize.y), Vector2.one / 2f, 16f);
  52.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement