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

ilmyapht  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(127)

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

zysjyyx4

zysjyyx41#

您无法将笔刷转换为颜色。笔刷的概念无法简化为颜色,因为它可能是颜色的渐层,或是影像等等。
这种转换只对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开发人员平台

vm0i2vca

vm0i2vca2#

可以将Brush转换为颜色,但是你必须明确地写出来。要做到这一点,只需这样做:

StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}

只要您正确地指定***Background***属性,**每一个 UIElement 都适用。

vktxenjb

vktxenjb3#

如果要将其转换为字符串,然后将字符串转换为字节,再将字节转换为颜色,则有一种解决方法:

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

在最后一行中,您获取十六进制字符串值并将其转换为字节。
确保你的画笔是由一种单一的颜色组成的,而不是空的,否则你会得到一个异常。

相关问题