PNGファイルを読み込んでTextureとして使う方法

Textureとして使いたい場合

PNGファイルを読み込んでTextureとして使いたい場合は、LoadImageを使って次のような感じで実装できるみたいです。

string path = "texture.png";
byte[] bytes = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(bytes);

Texture2D(2, 2)としていますが、LoadImage実行後にサイズも更新されるそうなので特に気にする必要はなさそうです。

Spriteとして使いたい場合

Spriteとして使いたい場合は

Rect rect = new Rect(0f, 0f, texture.width, texture.height);
Sprite sprite = Sprite.Create(texture, rect, Vector2.zero);

として使えるそうです。

リンク

Unity – Scripting API: ImageConversion.LoadImage
https://docs.unity3d.com/ScriptReference/ImageConversion.LoadImage.html

Unity – Scripting API: Sprite.Create
https://docs.unity3d.com/ScriptReference/Sprite.Create.html

Unity – Scripting API: Windows.File.ReadAllBytes
https://docs.unity3d.com/ScriptReference/Windows.File.ReadAllBytes.html

Makefileにforループを書く方法

シェルスクリプトのforをMakefileに書くと次のようなエラーになってしまいます。

example0:
--TAB-- for i in 1 2 3 4 5;
--TAB-- do
--TAB--   echo $$i
--TAB-- done

実行結果

$ make example0
for i in 1 2 3 4 5;
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [makefile:2: example0] Error 1

Makefileは基本的に1行ずつのコマンドを書くようになっていることが原因みたいです。ということで、Makefileでforループを使いたい場合は1行で書くようにすると良いみたいです。

example1: 1行でforループを書く方法

example1:
--TAB-- for i in 1 2 3 4 5; do echo $$i; done

実行結果

$ make example1
for i in 1 2 3 4 5; do echo $i; done
1
2
3
4
5

example2: バックスラッシュ\を使って1行にする方法

example2:
--TAB-- for i in 6 7 8 9 10; do \
--TAB--   echo $$i; \
--TAB-- done

実行結果

$ make example2
for i in 6 7 8 9 10; do \
  echo $i; \
done
6
7
8
9
10

どちらも結果は同じになりますので、読み易い書き方を使ってみてください。

※変数参照は$でなく$$にしないと使えないので気を付けてください。

リンク

Multiline bash commands in makefile – Stack Overflow
https://stackoverflow.com/questions/10121182/multiline-bash-commands-in-makefile

How to write loop in a Makefile? – Stack Overflow
https://stackoverflow.com/questions/1490949/how-to-write-loop-in-a-makefile

ImageMagickのconvertコマンドでサムネイル画像を作成

ImageMagickのconvertコマンドを使って画像をresize & cropする方法を調べてみました。

オリジナルの画像(src.jpg)

アスペクトを維持して画像全体が含まれるようにリサイズ

$ convert -resize 200x200 -gravity Center -extent 200x200 src.jpg dst.jpg

CSSのbackground-size:containのような感じです。-gravity Centerはリサイズ後の配置に影響します。NorthWest/North/NorthEast/West/Center/East/SouthWest/South/SouthEastが使えます。

アスペクトを無視してリサイズ

$ convert -resize 200x200! -extent 200x200 src.jpg dst.jpg

アスペクトを維持して余白がないようにリサイズ

$ convert -resize 200x200^ -gravity Center -extent 200x200 src.jpg dst.jpg

CSSのbackground-size:coverのような感じです。切り取る部分を変更したい場合は-gravity Centerの部分を変更してみてください。

Windows環境で200x200^がうまく動作しない場合は200x200^^を試してみるとうまく動作する場合もあるみたいです。