Silverlight/WPF使用十六进制颜色设置椭圆形

4

我想在代码中设置椭圆对象的颜色。目前,我是通过使用SolidColorBrush方法来实现的。是否有一种方式可以像CSS中那样插入十六进制的颜色值?

这是我正在使用的代码:

ellipse.Fill = new SolidColorBrush(Colors.Yellow);

考虑到大多数 XAML 使用十六进制字符串表示颜色,无法在 Silverlight 中执行此操作非常奇怪。因此,他们有代码,但是没有以一种可以在代码后台(C#)中使用的方式向我们公开它。 - RyBolt
7个回答

4

这样做可以起作用

ellipse.Fill = 
    new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF00DD")); 

(编辑:看起来这只适用于WPF。Alex Golesh在这里发表了他关于Silverlight ColorConverter的博客文章)
尽管我更喜欢Color.FromRgb方法。
byte r = 255;
byte g = 0;
byte b = 221;
ellipse.Fill = new SolidColorBrush(Color.FromRgb(r,g,b)); 

我需要继承什么才能使用ColorConverter? - Drahcir
在WPF中,它位于System.Windows.Media命名空间中,在Silverlight中则没有。请参阅我的编辑。 - Ray

2

From MSDN

SolidColorBrush mySolidColorBrush = new SolidColorBrush();

// Describes the brush's color using RGB values. 
// Each value has a range of 0-255.
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);
myRgbRectangle.Fill = mySolidColorBrush;   

2
我编写了一个简单的颜色转换函数来解决这个问题。快乐的表情实际上是数字8和一个括号,像这样:8)。

2
当然,你也可以像下面这样做(使用FromArgb函数中的十六进制数):
SolidColorBrush mySolidColorBrush = new SolidColorBrush();

// Describes the brush's color using RGB HEX values. 
// Each value has a range of 0-255. Use 0x for HEX numbers
mySolidColorBrush.Color = Color.FromArgb(255, 0xFF, 0xC0, 0xD0);
myRgbRectangle.Fill = mySolidColorBrush;

1

使用十六进制值:

 your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

1

另一个,小巧、快速且实用:

public static Color ToColor(this uint argb)
{
    return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                          (byte)((argb & 0xff0000) >> 0x10),
                          (byte)((argb & 0xff00) >> 8),
                          (byte)(argb & 0xff));
}

在代码中使用:

SolidColorBrush scb  = new SolidColorBrush (0xFFABCDEF.ToColor());

当然需要使用0xFFFFFFFF(uint)表示法而不是“#FFFFFFFF”(字符串),但我相信这并不是什么大问题。

0

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