所以,在我的程序中我有3个滑块,SliderRed,SliderGreen,Slider Blue.它们的最大值都是255. EndColor当我移动滑块时,控件调用正确地改变了颜色,但我还没有找到一种方法来获取hexcode.text(Textblock)将画笔或颜色转换为十六进制值,如#FF0000.
我应该用什么来工作呢?
public void SliderChanged()
{
byte r = byte.Parse(sliderRed.Value.ToString());
byte g = byte.Parse(sliderGreen.Value.ToString());
byte b = byte.Parse(sliderBlue.Value.ToString());
EndColor.Background = new SolidColorBrush(Color.FromArgb(255, r, g, b));
hexcode.Text = EndColor.Background.ToString(); //Something like this
}
Run Code Online (Sandbox Code Playgroud)
我只需要hexcode.Text显示十六进制值.
首先让我指出,假设您的滑块value属性返回一个int,您将转换int为a string然后再转回.这不是必需的.代替
byte r = byte.Parse(sliderRed.Value.ToString());
Run Code Online (Sandbox Code Playgroud)
你需要做的就是
byte r = (byte)sliderRed.Value;
Run Code Online (Sandbox Code Playgroud)
这会绕过字符串转换.将某些东西转换为字符串然后将其从字符串转换回其他东西是一种代码气味,应该让你停下来思考是否有更好的方法.
要将颜色转换为十六进制代码很简单,因为您已经拥有R,G和B值.所有你需要的是:
hexCode.Text = string.Format("#{0:X2}{1:X2}{2:X2}", r, g, b);
Run Code Online (Sandbox Code Playgroud)
使用格式字符串格式化数字会"X2"强制它以十六进制呈现,具有2位数字.所以你只需要为彼此相邻的所有三个执行此操作,并将哈希符号粘贴在前面.
编辑
如果您在代码的各个部分之间传递颜色数据,则应始终使用System.Drawing.Color对象执行此操作,然后在需要显示十六进制字符串时,请在此时生成该字符串.不要绕过十六进制字符串并Color在需要时将其转换回.还记得我说过把东西转换成字符串然后再回来是代码味道吗?
如果你发现你做了很多,那么添加扩展方法是有意义的,Color这样你就可以轻松地调用它.这是一个实现该方法的类:
static class ColorExtensions
{
public static string ToHexString(this System.Drawing.Color color)
{
return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}
}
Run Code Online (Sandbox Code Playgroud)
这将为所有Color值提供一个ToHexString()方法,您可以在上面的代码中使用如下方法:
var color = Color.FromArgb(255, r, g, b);
EndColor.Background = new SolidColorBrush(color);
hexcode.Text = color.ToHexString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1735 次 |
| 最近记录: |