来自文本框的 RGB 代码

RGB codes from text box

(首先,我是菜鸟,因为我 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)
    {

    }

只需使用 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);

在您的方法开头执行一次上述代码。