LoginSignup
17
12

More than 1 year has passed since last update.

[Unity2D]長方形のTexture2Dのデータから中央部分を正方形に切り出したい

Last updated at Posted at 2015-09-10

背景

例えば、1280 × 720 または 720 × 1280 のようなTexture2Dのデータから、720 × 720 で中央部分を切り出したい。

これを
スクリーンショット 2015-09-10 20.50.59.png

こんな風に
スクリーンショット 2015-09-10 20.51.52.png
したい。

作戦

  1. 縦と横の長さを比較
  2. 長い方の余白値(左右 or 上下)を求める
  3. その余白を半分にして(左右 or 上下)からTexture2DのGetPixelsを使って切り出す

コード

clipTexture2D_v2.cs

Texture2D getCenterClippedTexture(Texture2D texture)
{
    Color[] pixel;
    Texture2D clipTex;
    int textureWidth = texture.width;
    int textureHeight = texture.height;

    if (textureWidth == textureHeight)
        return texture;
    if (textureWidth > textureHeight) { // 横の方が長い
        int x = (textureWidth - textureHeight) / 2;
        // GetPixels (x, y, width, height) で切り出せる
        pixel = texture.GetPixels(x, 0, textureHeight, textureHeight);
        // 横幅,縦幅を指定してTexture2Dを生成
        clipTex = new Texture2D(textureHeight, textureHeight); 
    }
    else { // 縦の方が長い
        int y = (textureHeight - textureWidth) / 2;
        pixel = texture.GetPixels(0, y, textureWidth, textureWidth);
        clipTex = new Texture2D(textureWidth, textureWidth);
    }
    clipTex.SetPixels(pixel);
    clipTex.Apply();
    return clipTex;
}

まとめ

UnityのTexture2Dでは GetPixelsを用いてTexture2Dのデータを切り出すことができる。
切り出したTexture2DのデータをSetPixelsで新しく生成したTexture2Dに貼り付けて返す。

参考文献

Texture2DからSpriteを生成する - のしメモ -アプリ開発ブログ-

17
12
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12