Рисуване на изображения с помощта на Graphics
Рисуване на изображения с помощта на Graphics
С библиотеката Aspose.PSD можете да рисувате прости форми като линии, правоъгълници и кръгове, както и сложни форми като многоъгълници, криви, дъги и Безиеови форми. Библиотеката Aspose.PSD създава такива форми, използвайки класа Graphics, който принадлежи на пространството имена Aspose.PSD. Обектите Graphics са отговорни за извършването на различни операции по рисуване върху изображение, като по този начин променят повърхността на изображението. Класът Graphics използва различни помощни обекти, за да подобри формите:
- Моливи, за рисуване на линии, ограждащи форми или визуализиране на други геометрични представления.
- Четки, за дефиниране на начина, по който се запълват области.
- Шрифтове, за дефиниране на формата на символите на текста.
Рисуване с класа 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); | |
} |
Изчистете повърхността
Изчистете повърхността на 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, за да се уверим, че те са диспозирани правилно.