32

Monotouchで16進値からUIColorを取得するには?

4

4 に答える 4

46

Objective C のソリューションをいくつか見つけましたが、Monotouch に特化したソリューションはありませんでした。IOS の最も一般的なソリューションに基づいて拡張メソッドを開発することになりました。

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)
            );
        }
    }

次のように使用します。

new UIColor().FromHex(0x4F6176);

Update、Monotouch 5.4 UIColor にはパラメーターなしのコンストラクターがないため、次のように使用するようです。

 UIColor.Clear.FromHex(0xD12229);
于 2012-04-25T07:10:14.720 に答える
40

Xamarin.Forms を使用している場合、これが役立つ場合があります。

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

...
Color.FromHex("#00FF00").ToUIColor();
于 2016-12-08T18:34:03.240 に答える
31

これは、cssのような文字列を使用できるようにするものです。

UIColor textColorNormal = UIColor.Clear.FromHexString("#f4f28d", 1.0f);

そしてここにクラスがあります:

using System;
using System.Drawing;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Globalization;

namespace YourApp
{
    public static class UIColorExtensions
    {
        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));

            }
        }
    }   
}
于 2013-01-31T01:05:02.537 に答える