Skip to content

Instantly share code, notes, and snippets.

@enue
Created September 8, 2016 08:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enue/0f5056697ef73102cbf17c5ba26624a2 to your computer and use it in GitHub Desktop.
Save enue/0f5056697ef73102cbf17c5ba26624a2 to your computer and use it in GitHub Desktop.
立ち絵の透明部分をトリミングする
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace TSKT
{
public class ImageTrimmer : AssetPostprocessor
{
static bool IsTarget(string path)
{
if (path.StartsWith("Assets/Resources/Dialogs"))
{
return true;
}
return false;
}
void OnPostprocessTexture(Texture2D texture)
{
if (!IsTarget(assetPath))
{
return;
}
Trim(texture);
}
void Trim(Texture2D texture)
{
var originalWidth = texture.width;
var pixels = texture.GetPixels();
var trimmingSize = GetTrimmingSize(pixels, originalWidth, texture.height);
if (trimmingSize > 0)
{
texture.Resize(originalWidth - trimmingSize * 2, texture.height);
var newPixels = new Color[texture.width * texture.height];
for (int y = 0; y < texture.height; ++y)
{
System.Array.Copy(pixels, trimmingSize + y * originalWidth, newPixels, y * texture.width, texture.width);
}
texture.SetPixels(newPixels);
}
}
int GetTrimmingSize(Color[] pixels, int textureWidth, int textureHeight)
{
for (int x = 0; x < textureWidth / 2; ++x)
{
for (int y = 0; y < textureHeight; ++y)
{
{
var color = pixels[x + y * textureWidth];
if (color.a != 0f)
{
return x;
}
}
{
var color = pixels[textureWidth - x - 1 + y * textureWidth];
if (color.a != 0f)
{
return x;
}
}
}
}
return textureWidth / 2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment