unity顏色轉換之字符串轉Color

unity顏色轉換之字符串轉Color

在unity開發引擎中,顏色的表示方式有許多中,其中一種是字符串,還有一種是Color這個被封裝好的結構體,那麼如何將一組字符串轉換為Color(rgba)呢?請看下面代碼演示:

unity顏色轉換之字符串轉Color

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text.RegularExpressions;

using UnityEngine;

public static class ColorEX

{

/// <summary>

/// 將字符串轉換為Color

///

/// <param>不帶#號6位的16進制顏色 帶#號自動去掉

/// <returns>

public static Color CreateColor(this Color color, string colorString)

{

float red = 0, green = 0, blue = 0;

char[] rgb;

if (colorString.Contains("#"))

{

colorString = colorString.Replace("#", "");

}

colorString = Regex.Replace(colorString.ToLower(), "[g-zG-Z]", "");

switch (colorString.Length)

{

case 6:

rgb = colorString.ToCharArray();

red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);

green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);

blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);

break;

}

color = new Color(red / 255, green / 255, blue / 255);

return color;

}

public static Color CloneColor(this Color color)

{

return new Color(color.r, color.g, color.b, color.a);

}

}

使用:

Color _editorLabelColor = (new Color()).CreateColor("CA6E0C");


分享到:


相關文章: