Рисование изображений с использованием Graphics

Рисование изображений с использованием Graphics

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

  • Ручки (Pens), для рисования линий, контуров форм или отображения других геометрических представлений.
  • Кисти (Brushes), для определения заполнения областей.
  • Шрифты (Fonts), для определения формы символов текста.

Рисование с использованием класса Graphics

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

  1. Создать изображение.
  2. Создать и инициализировать объект Graphics.
  3. Очистить поверхность.
  4. Нарисовать эллипс.
  5. Нарисовать заполненный многоугольник и сохранить изображение.

Примеры программирования

Создание изображения

Начните с создания изображения, используя любой из описанных методов в разделе Создание файлов.

String dataDir = Utils.getDataDir(DrawingBezier.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Bezier.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (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.getYellow());
// Initializes the instance of PEN class with black color and width
Pen BlackPen = new Pen(Color.getBlack(), 3);
float startX = 10;
float startY = 25;
float controlX1 = 20;
float controlY1 = 5;
float controlX2 = 55;
float controlY2 = 10;
float endX = 90;
float endY = 25;
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes.
graphic.drawBezier(BlackPen, startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
// export image to bmp file format.
image.save(outpath, saveOptions);
}

Создание и инициализация объекта Graphics

Затем создайте и инициализируйте объект Graphics, передав объект Image в его конструктор.

String dataDir = Utils.getDataDir(DrawingArc.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Arc.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (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.getYellow());
// 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.getBlack()), 0, 0, width, height, startAngle, sweepAngle);
// export image to bmp file format.
image.save(outpath, saveOptions);
}

Очистка поверхности

Очистите поверхность Graphics, вызвав метод Clear класса Graphics и передавая цвет в качестве параметра. Этот метод заполнит поверхность Graphics переданным в аргументе цветом.

String dataDir = Utils.getDataDir(DrawingUsingGraphics.class) + "DrawingImages/";
// Create an instance of Image
try (PsdImage image = new PsdImage(500, 500)) {
Graphics graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.clear(Color.getWhite());
Pen pen = new Pen(Color.getBlue());
// 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));
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(image.getBounds(), Color.getRed(), Color.getWhite(), 45f);
// graphics.fillPolygon(linearGradientBrush, new Point(200, 200), new Point(400, 200), new Point(250, 350));
Point[] points = {new Point(200, 200), new Point(400, 200), new Point(250, 350)};
graphics.fillPolygon(linearGradientBrush, points);
// export modified image.
image.save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

Нарисовать эллипс

Вы можете заметить, что класс Graphics предоставляет множество методов для рисования и заполнения форм. Полный список методов можно найти в справочнике API Aspose.PSD для Java. Класс Graphics представляет несколько перегруженных версий метода DrawEllipse. Все эти методы принимают объект Pen в качестве первого аргумента. Последующие параметры используются для определения ограничивающего прямоугольника вокруг эллипса. Для данного примера используйте версию, принимающую объект Rectangle в качестве второго параметра, чтобы нарисовать эллипс с использованием объекта Pen выбранного вами цвета.

String dataDir = Utils.getDataDir(DrawingEllipse.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Ellipse.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (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.getYellow());
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.drawEllipse(new Pen(Color.getRed()), new Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having solid brush with blue color and a surrounding Rectangle
graphic.drawEllipse(new Pen(new SolidBrush(Color.getBlue())), new Rectangle(10, 30, 80, 40));
// export image to bmp file format.
image.save(outpath, saveOptions);
}

Нарисовать заполненный многоугольник

Затем нарисуйте многоугольник, используя LinearGradientBrush и массив точек. Класс Graphics предоставляет несколько перегруженных версий метода FillPolygon. Все они принимают объект Brush в качестве первого аргумента, определяя характеристики заливки. Второй параметр - это массив точек. Обратите внимание, что каждые две последовательные точки в массиве указывают сторону многоугольника.

String dataDir = Utils.getDataDir(DrawingUsingGraphics.class) + "DrawingImages/";
// Create an instance of Image
try (PsdImage image = new PsdImage(500, 500)) {
Graphics graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.clear(Color.getWhite());
Pen pen = new Pen(Color.getBlue());
// 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));
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(image.getBounds(), Color.getRed(), Color.getWhite(), 45f);
// graphics.fillPolygon(linearGradientBrush, new Point(200, 200), new Point(400, 200), new Point(250, 350));
Point[] points = {new Point(200, 200), new Point(400, 200), new Point(250, 350)};
graphics.fillPolygon(linearGradientBrush, points);
// export modified image.
image.save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

Рисование изображений с использованием Graphics: Полный исходный код

String dataDir = Utils.getDataDir(DrawingUsingGraphics.class) + "DrawingImages/";
// Create an instance of Image
try (PsdImage image = new PsdImage(500, 500)) {
Graphics graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.clear(Color.getWhite());
Pen pen = new Pen(Color.getBlue());
// 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));
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(image.getBounds(), Color.getRed(), Color.getWhite(), 45f);
// graphics.fillPolygon(linearGradientBrush, new Point(200, 200), new Point(400, 200), new Point(250, 350));
Point[] points = {new Point(200, 200), new Point(400, 200), new Point(250, 350)};
graphics.fillPolygon(linearGradientBrush, points);
// export modified image.
image.save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}

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