さけのさかなのブログ

同人ゲーム開発やってます。Unity使ったりする。

【Unity】ARGB文字列をパースする

かゆいところ

 Unity標準機能のColorUtility.TryParseHtmlStringを使うと、#RRGGBBAAで指定された文字列をColorにパースすることができる。

 けど、世の中にはAARRGGBBもあるわけでして。

コード

Unity5.4.0p1

static public class ColorUtil
{
    static public bool TryParseArgbString(string argb, out Color color)
    {
        if (ColorUtility.TryParseHtmlString(argb, out color))
        {
            var a = color.r;
            color.r = color.g;
            color.g = color.b;
            color.b = color.a;
            color.a = a;
            return true;
        }
        return false;
    }
}

 αのないRGBを入れたら変なことになるんだけど、そこまで対応するなら自分で書いた方がよさげ。

public static Color32 ParseArgb(string argb)
{
    var value = System.Convert.ToInt32(argb.TrimStart('#'), 16);
    var a = (value >> 24) & 0xff;
    var r = (value >> 16) & 0xff;
    var g = (value >> 8) & 0xff;
    var b = value & 0xff;

    return new Color32((byte)r, (byte)g, (byte)b, (byte)a);
}

argb parser · GitHub