По рабочей программе — практическая работа №9, 4 часа (2 пары). Первая пара — текстовый вывод: цвет, позиционирование, таблица. Вторая — графический вывод средствами графических библиотек Windows: GDI+ в окне и GDI в файл.
Научиться управлять текстовым выводом в консоли и рисовать графику средствами библиотек Windows: линии, фигуры, текст, график по данным. Понять, чем вывод знакоместами отличается от вывода пикселями.
Текстовый режим. Экран консоли — сетка знакомест: у каждого символа есть координаты (столбец, строка), цвет символа и цвет фона.
Графический режим. Картинка состоит из пикселей. Программа рисует не сама, а просит графическую библиотеку: «линия отсюда досюда», «прямоугольник», «текст в точке». Библиотека переводит команды в пиксели окна, принтера или картинки в памяти.
| Библиотека | Где находится | Как вызывать из C# |
|---|---|---|
| GDI | gdi32.dll — функции Windows | DllImport: LineTo, Rectangle, Ellipse, TextOutW |
| GDI+ | gdiplus.dll, в .NET — System.Drawing | класс Graphics: DrawLine, FillEllipse, DrawString |
Любое рисование строится одинаково: получить контекст устройства (на чём рисовать), выбрать перо (линии) и кисть (заливка), нарисовать, освободить созданные объекты.
using System;
string[] products = { "Процессор", "Память 16 ГБ", "SSD 1 ТБ", "Видеокарта" };
int[] stock = { 12, 3, 0, 7 };
decimal[] prices = { 21990m, 4590m, 6990m, 45990m };
ConsoleColor oldForeground = Console.ForegroundColor;
ConsoleColor oldBackground = Console.BackgroundColor;
Console.Clear();
try
{
const int Left = 4;
const int Top = 2;
Console.SetCursorPosition(Left, Top);
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.White;
Console.Write($" {"Товар",-16}{"Остаток",8}{"Цена, ₽",12} ");
Console.BackgroundColor = oldBackground;
for (int i = 0; i < products.Length; i++)
{
Console.SetCursorPosition(Left, Top + 1 + i);
Console.ForegroundColor = stock[i] == 0 ? ConsoleColor.Red
: stock[i] < 5 ? ConsoleColor.Yellow
: ConsoleColor.Green;
Console.Write($" {products[i],-16}{stock[i],8}{prices[i],12:N0} ");
}
Console.SetCursorPosition(Left, Top + products.Length + 2);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Красный — нет на складе, жёлтый — заканчивается.");
Console.SetCursorPosition(0, Top + products.Length + 4);
}
finally
{
Console.ForegroundColor = oldForeground;
Console.BackgroundColor = oldBackground;
}
Console.WindowWidth и Console.WindowHeight, чтобы таблица помещалась при любом размере окна.┌ ─ ┐ │ └ ┘ вокруг таблицы.finally и остановите программу исключением посередине. В каком цвете останется консоль? Верните finally.Выведите остатки товаров из задания 1 горизонтальной диаграммой: один символ █ на единицу товара, цвет — как в таблице, подпись — название и число.
Программа открывает окно и рисует в нём график средней температуры по месяцам. Рисование происходит в обработчике события Paint — Windows вызывает его каждый раз, когда окно нужно перерисовать.
Проекту нужна библиотека Windows Forms. В файле .csproj целевая платформа должна быть net8.0-windows, и добавлена строка <UseWindowsForms>true</UseWindowsForms>.
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading;
using System.Windows.Forms;
double[] temperatures = { -7.5, -6.0, -0.5, 7.0, 14.5, 18.0, 20.5, 18.5, 12.5, 6.0, -0.5, -5.0 };
string[] months = { "янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек" };
// Окна Windows Forms работают в потоке с однопоточной моделью (STA)
var window = new Thread(() =>
{
var form = new Form
{
Text = "Температура по месяцам",
ClientSize = new Size(760, 420),
BackColor = Color.White,
};
form.Paint += (sender, e) => DrawChart(e.Graphics, form.ClientSize);
form.Resize += (sender, e) => form.Invalidate();
Application.Run(form);
});
window.SetApartmentState(ApartmentState.STA);
window.Start();
window.Join();
void DrawChart(Graphics g, Size size)
{
const int Left = 60;
const int Top = 60;
const int Margin = 40;
const double Min = -10;
const double Max = 25;
int width = size.Width - Left - Margin;
int height = size.Height - Top - Margin;
float Y(double value) => (float)(Top + (Max - value) / (Max - Min) * height);
float X(int index) => Left + index * width / (float)(temperatures.Length - 1);
g.SmoothingMode = SmoothingMode.AntiAlias;
using var titleFont = new Font("Segoe UI", 14, FontStyle.Bold);
using var font = new Font("Segoe UI", 9);
using var gridPen = new Pen(Color.Gainsboro);
using var axisPen = new Pen(Color.Black, 2);
using var linePen = new Pen(Color.RoyalBlue, 3);
using var pointBrush = new SolidBrush(Color.OrangeRed);
g.DrawString("Средняя температура, °C", titleFont, Brushes.Black, Left, 16);
for (int t = -10; t <= 25; t += 5)
{
g.DrawLine(gridPen, Left, Y(t), Left + width, Y(t));
g.DrawString(t.ToString(), font, Brushes.DimGray, 22, Y(t) - 8);
}
g.DrawLine(axisPen, Left, Y(0), Left + width, Y(0));
g.DrawLine(axisPen, Left, Top, Left, Top + height);
var points = new PointF[temperatures.Length];
for (int i = 0; i < temperatures.Length; i++)
{
points[i] = new PointF(X(i), Y(temperatures[i]));
g.DrawString(months[i], font, Brushes.DimGray, X(i) - 12, Top + height + 6);
}
g.DrawLines(linePen, points);
foreach (PointF point in points)
{
g.FillEllipse(pointBrush, point.X - 5, point.Y - 5, 10, 10);
}
}
DrawString).Color.FromArgb(60, Color.RoyalBlue) и FillPolygon.FillRectangle), столбцы с отрицательной разницей к прошлой неделе — красным цветом.Функции gdi32.dll рисуют в контекст устройства. Здесь контекст создаётся в памяти, картинка сохраняется в файл BMP — окно не нужно.
using System;
using System.IO;
using System.Runtime.InteropServices;
const int Width = 400;
const int Height = 240;
const uint Whiteness = 0x00FF0062;
const string FileName = "gdi-рисунок.bmp";
var header = new BITMAPINFOHEADER
{
biSize = Marshal.SizeOf<BITMAPINFOHEADER>(),
biWidth = Width,
biHeight = Height, // положительная высота: строки снизу вверх
biPlanes = 1,
biBitCount = 32,
};
IntPtr dc = CreateCompatibleDC(IntPtr.Zero);
IntPtr bitmap = CreateDIBSection(dc, ref header, 0, out IntPtr pixels, IntPtr.Zero, 0);
IntPtr oldBitmap = SelectObject(dc, bitmap);
IntPtr pen = CreatePen(0, 3, Rgb(30, 90, 200));
IntPtr brush = CreateSolidBrush(Rgb(255, 200, 60));
IntPtr font = CreateFontW(-26, 0, 0, 0, 700, 0, 0, 0, 1, 0, 0, 5, 0, "Segoe UI");
try
{
PatBlt(dc, 0, 0, Width, Height, Whiteness); // белый фон
IntPtr oldPen = SelectObject(dc, pen);
IntPtr oldBrush = SelectObject(dc, brush);
Rectangle(dc, 20, 20, 180, 140);
Ellipse(dc, 210, 20, 380, 140);
MoveToEx(dc, 20, 210, IntPtr.Zero);
LineTo(dc, 380, 210);
IntPtr oldFont = SelectObject(dc, font);
SetBkMode(dc, 1); // прозрачный фон под текстом
SetTextColor(dc, Rgb(40, 40, 40));
const string Caption = "Рисунок средствами GDI";
TextOutW(dc, 24, 160, Caption, Caption.Length);
SelectObject(dc, oldFont);
SelectObject(dc, oldBrush);
SelectObject(dc, oldPen);
int imageBytes = Width * Height * 4;
var data = new byte[imageBytes];
Marshal.Copy(pixels, data, 0, imageBytes);
using (var file = new BinaryWriter(File.Create(FileName)))
{
file.Write((byte)'B');
file.Write((byte)'M');
file.Write(14 + header.biSize + imageBytes); // размер файла
file.Write(0); // зарезервировано
file.Write(14 + header.biSize); // где начинаются пиксели
file.Write(header.biSize);
file.Write(Width);
file.Write(Height);
file.Write((short)1);
file.Write((short)32);
file.Write(0); // без сжатия
file.Write(imageBytes);
file.Write(0);
file.Write(0);
file.Write(0);
file.Write(0);
file.Write(data);
}
Console.WriteLine($"Рисунок сохранён: {Path.GetFullPath(FileName)}");
}
finally
{
SelectObject(dc, oldBitmap);
DeleteObject(font);
DeleteObject(brush);
DeleteObject(pen);
DeleteObject(bitmap);
DeleteDC(dc);
}
static uint Rgb(byte red, byte green, byte blue) => (uint)(red | (green << 8) | (blue << 16));
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFOHEADER info, uint usage, out IntPtr bits, IntPtr section, uint offset);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr gdiObject);
[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr gdiObject);
[DllImport("gdi32.dll")]
static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern IntPtr CreatePen(int style, int width, uint color);
[DllImport("gdi32.dll")]
static extern IntPtr CreateSolidBrush(uint color);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CreateFontW(int height, int width, int escapement, int orientation, int weight,
uint italic, uint underline, uint strikeOut, uint charSet, uint outputPrecision,
uint clipPrecision, uint quality, uint pitchAndFamily, string faceName);
[DllImport("gdi32.dll")]
static extern bool PatBlt(IntPtr hdc, int x, int y, int width, int height, uint rop);
[DllImport("gdi32.dll")]
static extern bool Rectangle(IntPtr hdc, int left, int top, int right, int bottom);
[DllImport("gdi32.dll")]
static extern bool Ellipse(IntPtr hdc, int left, int top, int right, int bottom);
[DllImport("gdi32.dll")]
static extern bool MoveToEx(IntPtr hdc, int x, int y, IntPtr previous);
[DllImport("gdi32.dll")]
static extern bool LineTo(IntPtr hdc, int x, int y);
[DllImport("gdi32.dll")]
static extern int SetBkMode(IntPtr hdc, int mode);
[DllImport("gdi32.dll")]
static extern uint SetTextColor(IntPtr hdc, uint color);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
static extern bool TextOutW(IntPtr hdc, int x, int y, string text, int length);
[StructLayout(LayoutKind.Sequential)]
struct BITMAPINFOHEADER
{
public int biSize;
public int biWidth;
public int biHeight;
public short biPlanes;
public short biBitCount;
public int biCompression;
public int biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public int biClrUsed;
public int biClrImportant;
}
gdi-рисунок.bmp просмотрщиком и приложите скриншот.LineTo), окно и подпись с вашей фамилией.finally в контекст сначала возвращается старая картинка, а только потом удаляются перо, кисть и шрифт.| Текстовый режим | Графический режим | |
|---|---|---|
| единица вывода | ||
| как задаётся место | ||
| чем задаётся цвет | ||
| что можно нарисовать | ||
| какие функции использовали |
Paint, а не один раз при запуске?Файл Фамилия_Группа_ПР-09.docx или PDF: цель работы, код и скриншоты всех заданий, картинка «дом» из задания 4, заполненная таблица сравнения, ответы на контрольные вопросы, вывод.
dotnet run --project examples/src/Module11 -- pp09
dotnet run --project examples/src/Module13 -- p1.3.7