티스토리 뷰

반응형

Button 등의 컨트롤 개체에 효과를 넣어보기

button1

 

먼저, 클래스에 이벤트 핸들러 메서드를 정의하고

        private Color MapRainbowColor(float value, float red_value, float blue_value)
        {
            // Convert into a value between 0 and 1023.
            int int_value = (int)(1023 * (value - red_value) /
                (blue_value - red_value));

            // Map different color bands.
            if (int_value < 256)
            {
                // Red to yellow. (255, 0, 0) to (255, 255, 0).
                return Color.FromArgb(255, int_value, 0);
            }
            else if (int_value < 512)
            {
                // Yellow to green. (255, 255, 0) to (0, 255, 0).
                int_value -= 256;
                return Color.FromArgb(255 - int_value, 255, 0);
            }
            else if (int_value < 768)
            {
                // Green to aqua. (0, 255, 0) to (0, 255, 255).
                int_value -= 512;
                return Color.FromArgb(0, 255, int_value);
            }
            else
            {
                // Aqua to blue. (0, 255, 255) to (0, 0, 255).
                int_value -= 768;
                return Color.FromArgb(0, 255 - int_value, 255);
            }
        }
        
        public void RainbowPaintEvent(object sender, PaintEventArgs e)
        {
            Control ctrl = sender as Control;

            int wid = ctrl.ClientSize.Width;
            int hgt = ctrl.ClientSize.Height;

            for (int x = 0; x < wid; x++)
            {
                using (Pen the_pen = new Pen(MapRainbowColor(x, 0, wid)))
                {
                    e.Graphics.DrawLine(the_pen, x, 0, x, hgt);
                }
            }

            Font drawFont = ctrl.Font;
            SolidBrush drawBrush = new SolidBrush(ctrl.ForeColor);
            SolidBrush drawBrush2 = new SolidBrush(Color.Gray);

            RectangleF drawRect = new Rectangle(0, 0, ctrl.Width, ctrl.Height);
            RectangleF drawRect2 = new Rectangle(2, 2, ctrl.Width, ctrl.Height);

            StringFormat drawSF = new StringFormat();
            drawSF.LineAlignment = StringAlignment.Center;
            drawSF.Alignment = StringAlignment.Center;

            e.Graphics.DrawString(ctrl.Text, drawFont, drawBrush2, drawRect2, drawSF);
            e.Graphics.DrawString(ctrl.Text, drawFont, drawBrush, drawRect, drawSF);
        }

 

Paint 이벤트에 할당한다.

button1.Paint += RainbowPaintEvent;

Paint 이벤트가 있는 개체에서만 사용할 수 있다.

 

참조

Map numeric values to colors in a rainbow in C# - C# HelperC# Helper (csharphelper.com)
반응형
TAG
댓글
댓글쓰기 폼