文本框中的RGB代码

时间:2018-10-07 16:38:03

标签: c# wpf text textbox rgb

(首先,我是2周前刚开始学习C#的菜鸟) 我的老师给我做了一个练习:写一个画星的程序。让用户通过文本框确定R,G和B值,以便您的程序能够绘制任何颜色的星星!

我有这段代码,它绘制了一个星星,但是我不知道如何从文本框中获取数字以替换R,G和B。

    public MainWindow()
    {
        InitializeComponent();

        Line myLine = new Line();
        myLine.Stroke = new SolidColorBrush(Color.FromRgb(r, g, b));
        myLine.StrokeThickness = 2;
        myLine.X1 = 200;
        myLine.Y1 = 1;
        myLine.X2 = 80;
        myLine.Y2 = 350;
        caPaper.Children.Add(myLine);

        Line mLine = new Line();
        mLine.Stroke = new SolidColorBrush(Color.FromRgb(r, g, b));
        mLine.StrokeThickness = 2;
        mLine.X1 = 200;
        mLine.Y1 = 1;
        mLine.X2 = 320;
        mLine.Y2 = 350;
        caPaper.Children.Add(mLine);

        Line vLine = new Line();
        vLine.Stroke = new SolidColorBrush(Color.FromRgb(r, g, b));
        vLine.StrokeThickness = 2;
        vLine.X1 = 1;
        vLine.Y1 = 120;
        vLine.X2 = 320;
        vLine.Y2 = 350;
        caPaper.Children.Add(vLine);

        Line bLine = new Line();
        bLine.Stroke = new SolidColorBrush(Color.FromRgb(r, g, b));
        bLine.StrokeThickness = 2;
        bLine.X1 = 399;
        bLine.Y1 = 120;
        bLine.X2 = 80;
        bLine.Y2 = 350;
        caPaper.Children.Add(bLine);

        Line nLine = new Line();
        nLine.Stroke = new SolidColorBrush(Color.FromRgb(r, g, b));
        nLine.StrokeThickness = 2;
        nLine.X1 = 1;
        nLine.Y1 = 120;
        nLine.X2 = 399;
        nLine.Y2 = 120;
        caPaper.Children.Add(nLine);


    }

    private void txtR_TextChanged(object sender, TextChangedEventArgs e)
    {

    }

    private void txtG_TextChanged(object sender, TextChangedEventArgs e)
    {

    }

    private void txtB_TextChanged(object sender, TextChangedEventArgs e)
    {

    }

1 个答案:

答案 0 :(得分:1)

只需使用byte.Parse()即可解析文本框中的数字:

Color.FromRgb( byte.Parse(txtR.Text), byte.Parse(txt.G.Text), byte.Parse(txtB.Text));

甚至更好:

   byte r = byte.Parse(txtR.Text),
   g = byte.Parse(txt.G.Text),
   b =  byte.Parse(txtB.Text);

在方法开始时,一次执行以上代码。