Малювання зображень за допомогою графіки
Малювання зображень за допомогою графіки
З використанням бібліотеки Aspose.PSD ви можете малювати прості форми, такі як лінії, прямокутники і кола, а також складні форми, такі як багатокутники, криві, дуги та фігури Без’є. Бібліотека Aspose.PSD створює такі форми за допомогою класу Graphics, який знаходиться в просторі імен Aspose.PSD. Об’єкти Graphics відповідальні за виконання різних операцій зображення, тим самим змінюючи поверхню зображення. Клас Graphics використовує різноманітні допоміжні об’єкти для поліпшення форм:
- Pens, для малювання ліній, контурів фігур або інших геометричних подань.
- Brushes, для визначення заповнення областей.
- Fonts, для визначення форми символів тексту.
Малювання за допомогою класу Graphics
Нижче наведено приклад коду, що демонструє використання класу Graphics. Вихідний код прикладу розбито на кілька частин, щоб зберегти його простоту та зрозумілість. Крок за кроком приклади показують, як:
- Створити зображення.
- Створити та ініціалізувати об’єкт Graphics.
- Очистити поверхню.
- Намалювати еліпс.
- Намалювати заповнений багатокутник та зберегти зображення.
Приклади програмування
Створення Зображення
Почніть зі створення зображення за допомогою будь-яких методів, описаних у розділі Створення файлів.
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); | |
} |
Очистка Поверхні
Очистіть поверхню графіки, викликавши метод Clear класу 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()); | |
} |
Малювання зображень за допомогою графіки: Повний вихідний код
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, щоб забезпечити їх правильне видалення.