如何将画笔转换为颜色(UWP)?

4
我已经将“Windows.UI.Xaml.Media.Brush”转换为“Windows.UI.Color”。但是,VS返回错误。请告诉我如何正确进行此转换?

2
请在您的问题中添加一些代码和错误信息。 - Kalten
3个回答

9

你无法将画刷转换为颜色。画刷的概念不能简化为颜色,因为它可以是一组颜色的渐变或者是一个图像等。

转换只对SolidColorBrush这种特殊情况有意义。我猜这就是你想要的。以下是代码实现:

Windows.UI.Color colorFromBrush;
if (brush is SolidColorBrush)
    colorFromBrush = (brush as SolidColorBrush).Color;
else
    throw new Exception("Can't get color from a brush that is not a SolidColorBrush");

感谢,Stefan Wick - Windows 开发平台


精彩的解释 - AVK

1
你可以将Brush转换为颜色,但必须明确地编写它。 只需执行以下操作即可:
StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}

这适用于每个单独的UI元素,只要你正确地分配了背景属性。

0

如果你正在将它转换为字符串,然后将字符串转换为字节,最后将字节转换为颜色,那么有一个解决方法:

var brushString = Foreground.ToString(); // brushString equals "#FF000000" (in case of black brush)
var brushWithoutHash = brushString.Substring(1); // brushWithoutHash equals "FF000000"
var color = Color.FromArgb(Convert.ToByte(brushWithoutHash.Substring(0, 2), 16), Convert.ToByte(brushWithoutHash.Substring(2, 2), 16), Convert.ToByte(brushWithoutHash.Substring(4, 2), 16), Convert.ToByte(brushWithoutHash.Substring(6, 2), 16));

在最后一行,您将获取十六进制字符串值并将其转换为字节。

确保您的画笔只使用单一颜色而不是空值,否则会出现异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接