【问题标题】:Winrt / XAML / C++ : Get Color from String ValueWinrt / XAML / C++:从字符串值中获取颜色
【发布时间】:2012-08-29 07:36:20
【问题描述】:

我目前正在用 C++ 编写一些 WinRT 组件,我需要弄清楚如何获取颜色字符串(例如 "#FF448DCA" )并将其转换为 Color 以用于构造 SolidColorBrush .

WPF 中,我们有BrushConverter,但在WinRT 中似乎没有等效项

我可以在C# 中通过拆分字符串、转换为十六进制块等来做到这一点,但这超出了我目前的C++ 技能。

在我花大量时间尝试解决之前,有没有人能快速回答(我的 C++ 会改进,但我的交易线会受到影响)

谢谢

【问题讨论】:

标签: c++ xaml windows-8 windows-runtime c++-cx


【解决方案1】:

这是一个简短的示例,如何使用正则表达式完成此操作,使用 vs 2010 express 编写。这只是解析,稍后使用 Marc 写的 ColorHelper

#include <string>
#include <regex>

bool GetARGBFromS(const std::string& s, int& a, int& r, int& g, int& b) {   
    try {
        std::smatch m;
        if ( regex_search(s, m, std::regex("#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})")) ) {
            a = std::stoi(m[1].str(), 0, 16);
            r = std::stoi(m[2].str(), 0, 16);
            g = std::stoi(m[3].str(), 0, 16);
            b = std::stoi(m[4].str(), 0, 16);
        }   
        else
            return false;
    }
    catch(...){ /*should catch/report specific exceptions, but thats just example*/ return false; }
    return true;
}

int main() {

    int a,r,g,b;
    if ( GetARGBFromS("#FF448DCA", a, r, g, b) )
    {}

    return 0;
}

【讨论】:

  • 仅仅因为我们可以使用正则表达式并不意味着我们应该......更简单/更快/更容易return std::swscanf(s.c_str(), L"#%2x%2x%2x%2x", &amp;a, &amp;r, &amp;g, &amp;b) == 4;怎么样? (GetARGBFromS 也可以修改为 wchar_t const*,因为我们在这里并不需要 std::string。)
  • 哇,这正是我想要的,谢谢。我将对其进行修改以从解析的颜色中返回一个 SolidColorBrush(使用 ColorHelper)。谢谢
【解决方案2】:

很遗憾,您需要将其转换为离散字节值。

一旦有了这些,您就可以使用 ColorHelper 类 (http://msdn.microsoft.com/en-us/library/windows/apps/hh747822.aspx) 将它们转换为 Color 结构(没有C++ 中的 Color.FromArgb 方法)。

【讨论】:

    【解决方案3】:

    这是我的做法。

            public static Brush ColorToBrush(string color)
        {
            color = color.Replace("#", "");
            if (color.Length == 6)
            {
                return new SolidColorBrush(ColorHelper.FromArgb(255,
                    byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                    byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                    byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
            }
            else
            {
                return null;
            }
        }
    

    致电

    textbox1.BorderBrush = ColorToBrush("#ffff00");
    

    【讨论】:

      猜你喜欢
      • 2017-05-28
      • 2013-01-31
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2012-06-13
      相关资源
      最近更新 更多