forked from aki-art/ONI-Mods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpriteHelper.cs
74 lines (58 loc) · 1.77 KB
/
SpriteHelper.cs
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
using System;
using UnityEngine;
namespace Backwalls
{
public class SpriteHelper
{
public static Sprite GetSpriteForAtlas(TextureAtlas atlas)
{
if(Application.platform != RuntimePlatform.WindowsPlayer)
{
// TODO: this is a mess that will work 95% of the time
// need to figure out why this breaks with the proper cropping
var uvBox = GetUVBox(atlas);
var tex = atlas.texture;
var y = 1f - Mathf.FloorToInt(uvBox.y);
y = Mathf.Clamp01(y);
y *= tex.height;
y -= 208;
y = Mathf.Clamp(y, 0, 1024 - 208);
return Sprite.Create(tex, new Rect(0, y, 208, 208), Vector3.zero, 100);
}
var cropped = GetUITexture(atlas);
return Sprite.Create(cropped, new Rect(0, 0, cropped.width, cropped.height), Vector3.zero, 100);
}
public static Texture2D GetUITexture(TextureAtlas atlas)
{
var uvBox = GetUVBox(atlas);
var texWidth = atlas.texture.width;
var tex = atlas.texture;
var renderTexture = new RenderTexture(tex.width, tex.height, 32);
Graphics.Blit(tex, renderTexture);
var xOffset = (int)(uvBox.x * texWidth);
var size = (int)(uvBox.z * texWidth - xOffset);
var texture2D = new Texture2D(size, size, TextureFormat.RGBA32, false);
texture2D.ReadPixels(new Rect(0, 0, size, size), 0, 0);
texture2D.Apply();
return texture2D;
}
private static Vector4 GetUVBox(TextureAtlas atlas)
{
var num3 = atlas.items[0].name.Length - 4 - 8;
var startIndex = num3 - 1 - 8;
var uvBox = Vector4.zero;
for (var k = 0; k < atlas.items.Length; k++)
{
var item = atlas.items[k];
var value = item.name.Substring(startIndex, 8);
var requiredConnections = Convert.ToInt32(value, 2);
if (requiredConnections == 0)
{
uvBox = item.uvBox;
break;
}
}
return uvBox;
}
}
}