Have you ever felt that your Windows applications look a little boring and are missing that touch of visual style and creativity? I assume you have, so I’m going to show you how you can paint a gradient background for your Windows Forms. It might not sound like much but this goes a long way in making your interface more appealing to the end users of your application.
The .NET framework includes a class called System.Drawing.Drawing2D.LinearGradientBrush which is designed specifically for painting gradients. It accepts as parameters the coordinates of the object to paint, the two colours used to produce the gradient, and the angle of the gradient.
Now, let’s use this class to paint a gradient on our Windows Form.
We begin by overriding the form’s OnPaintBackground method like this:
protected override void OnPaintBackground(PaintEventArgs e)
{
}
This method will fire when the form is to be painted so it is the perfect event for us to paint our gradient in. Now that we have overridden the OnPaintBackground method we must create an instance of LinearGradientBrush and give it some parameters for our gradient. We must also paint the form using the Graphics‘ object FillRectangle method. The code for this is below:
protected override void OnPaintBackground(PaintEventArgs e)
{
using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
Color.Gray,
Color.Black,
90F))
{
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
}
Now to explain what is happening here – we are creating an instance of LinearGradientBrush and wrapping it inside the using keyword so that the object is automatically disposed of when the method exists. As the first parameter we are passing this.ClientRectangle which specifies the bounds of our form, which are also the bounds of our gradient. Next we are passing the colours to be used to create the gradient – Color.Gray, and Color.Black. With the fourth parameter we are telling the brush to paint the gradient at 90 degrees – i.e. vertical. And finally we are using the Graphics object of the form to actually paint the form using the brush we just created.
Now if you run the application you will get a form which looks like this:
Obviously by changing the values of the parameters you pass to LinearGradientBrush you can create many different effects.
There is one little problem with this code. If you try and resize the form, the gradient will not adjust to the new size. This problem is easily fixed though. Within your Form_Resize event call this.Invalidate() and everything will work fine. This invalidates the entire surface of the form and forces it to be redrawn.
private void Form1_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
And that’s it. You now know how to make your forms look a little better by using gradients.
I hope you enjoyed this article. Happy painting and stay tuned for more soon.
Dave
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Введение
Градиентная заливка – это плавный переход одного или нескольких цветов в другие, часто используемый для улучшения визуальной привлекательности приложений. В C#, градиент можно создать с помощью GDI+ (подсистема Windows для рендеринга 2D-графики), доступной через пространство имен System.Drawing.
Основы градиентной заливки
Градиенты бывают разных типов: линейные, радиальные, угловые и т.д. В этой статье мы сфокусируемся на линейной градиентной заливке.
Пример 1: Линейный градиент
Для начала, создадим простое оконное приложение на C#, в котором реализуем линейный градиент.
-
Создание проекта
Откройте Visual Studio и создайте новый проект Windows Forms App (.NET Framework).
-
Форма для отрисовки
В
Form1, где мы будем рисовать наш градиент, переопределим методOnPaint:protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); DrawLinearGradient(e.Graphics); } -
Реализация градиентной заливки
Добавим метод
DrawLinearGradient:private void DrawLinearGradient(Graphics graphics) { // Определение области для градиента Rectangle rect = new Rectangle(0, 0, this.Width, this.Height); // Создание градиента using (LinearGradientBrush brush = new LinearGradientBrush( rect, Color.Blue, // Начальный цвет Color.White, // Конечный цвет LinearGradientMode.Horizontal)) // Направление градиента { // Заливка области градиентом graphics.FillRectangle(brush, rect); } }В этом коде мы создаём
LinearGradientBrush, определяя область заливки и цвета градиента.LinearGradientModeопределяет направление изменения цвета.
Пример 2: Радиальный градиент
Радиальные градиенты в .NET Framework реализовать сложнее, поскольку для них нет встроенной поддержки, как для линейных. Но можно использовать методы рисования кругов с постепенным изменением цвета.
-
Реализация радиального градиента
Мы будем использовать метод
FillEllipseдля рисования последовательности вложенных кругов с изменением цвета.private void DrawRadialGradient(Graphics graphics) { int radius = Math.Min(this.Width, this.Height) / 2; Point center = new Point(this.Width / 2, this.Height / 2); // От центра к краям for (int r = radius; r > 0; r--) { int alpha = 255 - (r * 255 / radius); Color color = Color.FromArgb(alpha, Color.Blue); using (SolidBrush brush = new SolidBrush(color)) { graphics.FillEllipse(brush, center.X - r, center.Y - r, r * 2, r * 2); } } }Здесь каждый круг рисуется с определённой прозрачностью, которая уменьшается от центра к краям, создавая эффект радиального градиента.
Применение градиентной заливки
Градиентная заливка широко используется в пользовательских интерфейсах для создания более глубоких и динамичных визуальных эффектов. Применяется она как в дизайне элементов формы, так и при создании графических компонентов (например, фонов, кнопок).
Заключение
Градиентная заливка — мощный инструмент для улучшения визуального восприятия приложений. В C# существует множество способов её реализации, начиная от простых линейных и заканчивая сложными радиальными и угловыми градиентами. Экспериментируйте с различными типами и параметрами градиентов, чтобы найти то, что лучше всего подойдёт для вашего проекта.
Да-да, я знаю, что лучше не делать на Windows Forms красивые приложения – для этого есть WPF. Однако, если проект уже разросся, то переносить его из-за пары красивостей не хочется. Тем более, что при достаточной сноровке можно делать симпатичные кнопочки и на Windows Forms.
Итак, сначала создаем кнопку. Называем её неоригинально – button1. Сначала закругляем ей края при загрзуке формы (событие лоад):
System.Drawing.Drawing2D.GraphicsPath Button_Path = new System.Drawing.Drawing2D.GraphicsPath();
Button_Path.AddEllipse(-10, -9, this.button1.Width+20, 40);
Region Button_Region = new Region(Button_Path);
this.button1.Region = Button_Region;
Числа подбираются индивидуально — чтобы края у кнопки были закруглены равномерно — я же не заню, какого размера она у вас.
Теперь нам надо закрасить кнопку. Но не просто однотонно, а с градиентом. Это тоже реализуется довольно просто. В обработчик перерисовщика кнопки кидаем:
private void button1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(
new LinearGradientBrush(PointF.Empty, new PointF(0, button1.Height), Color.Black, Color.Green),
new RectangleF(PointF.Empty, button1.Size));
g.DrawString("Вход за преподавателя", new Font("Arial", 10), System.Drawing.Brushes.White, new Point(10, 3));
}
И получается вот такая картина:
Не сказать, чтобы очень красиво, но своей цели мы все же добились. Если вам требуется помощь программиста по C# или другим языкам программирования, то вы можете написать мне — за небольшую плату я вам с удовольствием помогу.
Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
