C#

024_scrollBar

iwannabebackendexpert 2022. 3. 30. 02:57

상단의 사진 처럼 스크롤바를 이용해 rgb색상을 panel에 출력해보도록하자.

도구상자에서 Panel를 끌어옴. 그리고 Label, ScrollBar 그리고 TextBox까지.

* scrollbar는 검색상자를 통해 검색하여서 끌어와야한다.

각각의 TextBox는 txtR,txtG,txtB로 이름을 바꾸어주자 + scrollbar도 scrR,scrG,scrB로 바꾸자.

 

public Form1() //생성자
        {
            InitializeComponent();

            this.BackColor = Color.LightSteelBlue;
            panel1.BackColor = Color.FromArgb(0, 0, 0);// =Color.Black;

            txtR.Text = "0";
            txtG.Text = "0";
            txtB.Text = "0";

            scrR.Maximum = 255 + 9;
            scrG.Maximum = 255 + 9;
            scrB.Maximum = 255 + 9;
        }

        private void scr_Scroll(object sender, ScrollEventArgs e)
        {
            txtR.Text = scrR.Value.ToString();
            txtG.Text = scrG.Value.ToString();
            txtB.Text = scrB.Value.ToString();
            panel1.BackColor = Color.FromArgb(scrR.Value, scrG.Value, scrB.Value);
        }

        private void txt_TextChanged(object sender, EventArgs e)
        {
            if (txtR.Text != "0" && txtG.Text != "0" && txtB.Text != "0")
            {
                scrR.Value = int.Parse(txtR.Text);
                scrG.Value = int.Parse(txtG.Text);
                scrB.Value = int.Parse(txtB.Text);
                panel1.BackColor = Color.FromArgb(scrR.Value, scrG.Value, scrB.Value);
            }
        }

 

Form1에서 기본설정을 해주자. this.Backcolor를 통해 배경색을 지정. Color.LightSteelBlue;

패널의 기본색깔의 (0,0,0)인 블랙으로 지정.

Maximum 함수를 통해서 범위를 지정해주어야함. 255+9 인 이유는 실제 스크롤바의 값을 출력해보면 255가 아니라 246까지 밖에 안나오기때문에, 246+9 =255으로 지정해주어야합니다.

 

scrollbar 세 가지를 모두 선택한 후 아래 사진처럼 속성창에서 번개모양의 이벤트를 클릭하면

작업창에서 scr_Scroll 로 바꾸어주자 그럼 세개중 하나의 값이 바뀌어도 같이 영향을 미친다.

그래서 아래의 코드블럭처럼 Scroll을 통해 값에 변화를 주어 문자열로 바꾸어 txtR,G,B에 값을 전달한다.

private void scr_Scroll(object sender, ScrollEventArgs e)
        {
            txtR.Text = scrR.Value.ToString();
            txtG.Text = scrG.Value.ToString();
            txtB.Text = scrB.Value.ToString();
            panel1.BackColor = Color.FromArgb(scrR.Value, scrG.Value, scrB.Value);
        }

이렇게되면 스크롤바의 오른쪽의 TextBox에 숫자가 스크롤바가 움직일때마다 값이 변화하게 된다.

 

private void txt_TextChanged(object sender, EventArgs e)
        {
            if (txtR.Text != "0" && txtG.Text != "0" && txtB.Text != "0")
            {
                scrR.Value = int.Parse(txtR.Text);
                scrG.Value = int.Parse(txtG.Text);
                scrB.Value = int.Parse(txtB.Text);
                panel1.BackColor = Color.FromArgb(scrR.Value, scrG.Value, scrB.Value);
            }
        }

 

이 코드블럭은 각각의 색상이 0이 아니라는 조건 하에 참이 되고. 텍스트박스에 입력된 값을 int.Parse를 통해 scrR,G,B.Value에 전달하게 된다. 이 값을 Color.FromArgb함수를 통해 패널에 색상이 조합되어 화면에 표현된다.

'C#' 카테고리의 다른 글

026_ComboBox  (0) 2022.04.06
025_ListBox  (0) 2022.04.06
023_ScoreCalculator  (0) 2022.03.30
022_Radiobutton & GroupBox  (0) 2022.03.30
021_CheckBox  (0) 2022.03.30