天天看點

Xamarin.iOS_16進制顔色轉UIColor

stackoverflow原文:http://stackoverflow.com/questions/10310917/uicolor-from-hex-in-monotouch

iOS裡面沒有現成API可以簡單實作16進制顔色值轉UIColor RGB的功能,而這個問答可以簡單的實作這個轉換,友善使用。

現成方案,直接對16進制進行10進制轉換,取得RBG對應的值,然後使用API中的FromRGB方法取得對應的UIColor顔色:

public static class UIColorExtensions
{
		public static UIColor FromHex(this UIColor color,int hexValue)
		{
			return UIColor.FromRGB(
				(((float)((hexValue & 0xFF0000) >> 16))/255.0f),
				(((float)((hexValue & 0xFF00) >> 8))/255.0f),
				(((float)(hexValue & 0xFF))/255.0f)
			);
		}

		public static UIColor FromHexString (this UIColor color, string hexValue, float alpha = 1.0f)
		{
			var colorString = hexValue.Replace ("#", "");
			if (alpha > 1.0f) {
				alpha = 1.0f;
			} else if (alpha < 0.0f) {
				alpha = 0.0f;
			}

			float red, green, blue;

			switch (colorString.Length) {
			case 3: // #RGB
				{
					red = Convert.ToInt32 (string.Format ("{0}{0}", colorString.Substring (0, 1)), 16) / 255f;
					green = Convert.ToInt32 (string.Format ("{0}{0}", colorString.Substring (1, 1)), 16) / 255f;
					blue = Convert.ToInt32 (string.Format ("{0}{0}", colorString.Substring (2, 1)), 16) / 255f;
					return UIColor.FromRGBA (red, green, blue, alpha);
				}
			case 6: // #RRGGBB
				{
					red = Convert.ToInt32 (colorString.Substring (0, 2), 16) / 255f;
					green = Convert.ToInt32 (colorString.Substring (2, 2), 16) / 255f;
					blue = Convert.ToInt32 (colorString.Substring (4, 2), 16) / 255f;
					return UIColor.FromRGBA (red, green, blue, alpha);
				}   

			default :
				throw new ArgumentOutOfRangeException (string.Format ("Invalid color value {0} is invalid. It should be a hex value of the form #RBG, #RRGGBB", hexValue));

			}
		}
}
           

調用:

//UIColor color = UIColor.Clear.FromHexString ("bab56e",1);
UIColor color = UIColor.Clear.FromHex (0xbab56e);	//ox16進制辨別
           
Xamarin.iOS_16進制顔色轉UIColor