Created
September 22, 2018 11:26
-
-
Save IJEMIN/0dfad012c0fc06edb62f0b746e30822b to your computer and use it in GitHub Desktop.
Sprite Merger in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
// Merge multiple Sprites as one sprite | |
public static class SpriteMerger { | |
public static Sprite MergeSprite(Sprite[] sprites) { | |
// 스프라이트 중 가장 큰 크기의 것으로 지정되야함 | |
int width = 0; | |
int height = 0; | |
foreach (var sprite in sprites) | |
{ | |
width = Mathf.Max(width, sprite.texture.width); | |
height = Mathf.Max(height, sprite.texture.height); | |
} | |
Texture2D mergedTexture = new Texture2D(width, height); | |
// mergedTexture.alphaIsTransparency = true; | |
for (int i = 0; i < width; i++) | |
{ | |
for (int j = 0; j < height; j++) | |
{ | |
mergedTexture.SetPixel(i, j, Color.clear); | |
} | |
} | |
// overdrawn by last one | |
foreach (var sprite in sprites) | |
{ | |
for (int y = 0; y < sprite.texture.height; y++) | |
{ | |
for (int x = 0; x < sprite.texture.width; x++) | |
{ | |
Color extractedPixel = sprite.texture.GetPixel(x, y); | |
Color replacedColor = mergedTexture.GetPixel(x, y); | |
replacedColor = (1.0f - extractedPixel.a) * replacedColor + extractedPixel.a * extractedPixel; | |
mergedTexture.SetPixel(x, y, replacedColor); | |
} | |
} | |
mergedTexture.Apply(); | |
} | |
Sprite mergedSprite = Sprite.Create(mergedTexture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f)); | |
return mergedSprite; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment