Малювання зображень за допомогою графіки

Малювання зображень за допомогою графіки

З бібліотекою Aspose.PSD можна малювати прості форми, такі як лінії, прямокутники і кола, а також складні форми, такі як багатокутники, криві, дуги та фігури Без’є. Бібліотека Aspose.PSD створює такі форми, використовуючи клас Graphics, який знаходиться в просторі імен Aspose.PSD. Об’єкти Graphics відповідальні за виконання різних операцій малювання на зображенні, змінюючи поверхню зображення. Клас Graphics використовує ряд допоміжних об’єктів для покращення форм:

  • Ручки для малювання ліній, обводок форм або відтворення інших геометричних представлень.
  • Кисті для визначення того, як заповнюються області.
  • Шрифти для визначення форми символів тексту.

Малювання за допомогою класу Graphics

Нижче наведено приклад коду, демонструючий використання класу Graphics. Джерелний код прикладу було розділено на кілька частин, щоб зробити його простішим та легким для розуміння. Крок за кроком приклади показують, як:

  1. Створити зображення.
  2. Створити та ініціювати об’єкт Graphics.
  3. Очистити поверхню.
  4. Намалювати еліпс.
  5. Намалювати заповнений багатокутник та зберегти зображення.

Приклади програмування

Створення зображення

Почніть зі створення зображення за допомогою будь-якого з методів, що описані в розділі “Створення файлів”.

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string loadpath = dataDir + "sample.psd";
string outpath = dataDir + "CoreDrawingFeatures.bmp";
// Create an instance of Image
using (PsdImage image = new PsdImage(loadpath))
{
// load pixels
var pixels = image.LoadArgb32Pixels(new Rectangle(0, 0, 100, 10));
for (int i = 0; i < pixels.Length; i++)
{
// specify pixel color value (gradient in this case).
pixels[i] = i;
}
// save modified pixels.
image.SaveArgb32Pixels(new Rectangle(0, 0, 100, 10), pixels);
// export image to bmp file format.
image.Save(outpath, new BmpOptions());
}

Створення та Ініціалізація об’єкта Graphics

Потім створіть та ініціалізуйте об’єкт Graphics, передаючи об’єкт Image до його конструктора.

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string outpath = dataDir + "Arc.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw an arc shape by specifying the Pen object having red black color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen and save all changes.
graphic.DrawArc(new Pen(Color.Black), 0, 0, width, height, startAngle, sweepAngle);
// export image to bmp file format.
image.Save(outpath, saveOptions);
}

Очищення Поверхні

Очистіть поверхню Graphics, викликавши метод Clear класу Graphics та передавши колір як параметр. Цей метод заповнює поверхню Graphics переданим кольором.

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// Create an instance of Image
using (PsdImage image = new PsdImage(500, 500))
{
var graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.Clear(Color.White);
var pen = new Pen(Color.Blue);
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
{
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
// export modified image.
image.Save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

Намалювати Еліпс

Ви можете помітити, що клас Graphics виклав безліч методів для малювання та заповнення форм. Ви знайдете повний список методів у довідці API Aspose.PSD для .NET. Клас Graphics виклав декілька версій методу DrawEllipse. Усі ці методи приймають об’єкт Pen як свій перший аргумент. Подальші параметри передаються для визначення описуючого прямокутника навколо еліпса. Для прикладу використайте версію, яка приймає об’єкт Rectangle в якості другого параметра, щоб намалювати еліпс за допомогою об’єкта Pen у вибраному вами кольорі.

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string loadpath = dataDir + "sample.psd";
string outpath = dataDir + "CoreDrawingFeatures.bmp";
// Create an instance of Image
using (PsdImage image = new PsdImage(loadpath))
{
// load pixels
var pixels = image.LoadArgb32Pixels(new Rectangle(0, 0, 100, 10));
for (int i = 0; i < pixels.Length; i++)
{
// specify pixel color value (gradient in this case).
pixels[i] = i;
}
// save modified pixels.
image.SaveArgb32Pixels(new Rectangle(0, 0, 100, 10), pixels);
// export image to bmp file format.
image.Save(outpath, new BmpOptions());
}

Намалювати Заповнений Багатокутник

Далі намалюйте багатокутник, використовуючи LinearGradientBrush та масив точок. Клас Graphics виклав декілька перегружених версій метода FillPolygon(). Всі вони приймають об’єкт Brush як перший аргумент, що визначає характеристики заливки. Другий параметр - це масив точок. Зверніть увагу, що кожні дві послідовні точки у масиві вказують на сторону багатокутника.

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// Create an instance of Image
using (PsdImage image = new PsdImage(500, 500))
{
var graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.Clear(Color.White);
var pen = new Pen(Color.Blue);
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
{
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
// export modified image.
image.Save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

Малювання зображень за допомогою графіки : Повний код

// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// Create an instance of Image
using (PsdImage image = new PsdImage(500, 500))
{
var graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.Clear(Color.White);
var pen = new Pen(Color.Blue);
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
{
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
// export modified image.
image.Save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

Всі класи, які реалізують IDisposable та мають доступ до некерованих ресурсів, створюються в операторі Using, щоб гарантувати їх правильне видалення.