>  기사  >  Java  >  Java의 2D 그래픽

Java의 2D 그래픽

PHPz
PHPz원래의
2024-08-30 16:06:061077검색

이미지 처리, 고급 그래픽 디자인 옵션, 기하학적 변환, 알파 합성 등과 같은 작업을 위한 Java 내장 기능을 포함하는 Java 2 플랫폼의 몇 가지 고급 기능을 사용하여 Java 프로그래밍을 사용하여 2D 그래픽을 구현할 수 있습니다. Java 2D 패키지에는 awt, awt.image, awt.color, awt.font, awt.geom, awt.print 및 awt.image.renderable과 같은 다양한 패키지가 제공됩니다. Java는 고품질 그래픽 결과, 매우 다양한 기하학적 디자인 옵션으로 인해 게임 개발자 커뮤니티에서 유명한 goto 옵션으로 문서 인쇄를 용이하게 하며 개발된 제품의 성능을 유지할 수 있게 해줍니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

자바 2D 렌더링

Java 2D API는 디스플레이 모니터나 프린터 등 다양한 장치에서 균일한 렌더링 모델을 지원합니다. 프로그램을 개발하는 동안 렌더링은 최종 구성 요소(프린터든 디스플레이 모니터든)에 관계없이 동일한 방식으로 작동합니다. 패키지는 최종 구성 요소를 기반으로 그래픽 컨텍스트를 자동으로 감지하고 변경합니다. Java 2D API는 향상된 그래픽 및 렌더링 기능을 지원하기 위해 Graphics 클래스를 확장하는 java.awt.Graphics2D로 구성됩니다.

패키지가 제공하는 기능은 다음과 같습니다.

  • 원시적인 기하학적 모양과 도형의 렌더링을 지원합니다.
  • 획을 사용하여 페인트 속성에 지정된 색상이나 패턴으로 도형의 내부를 채울 수 있는 옵션을 제공합니다.
  • 지정된 이미지를 렌더링할 수 있습니다.
  • 텍스트 문자열을 페인트 속성에 지정된 색상으로 채워진 글리프로 변환할 수 있습니다.

예시 #1

동일한 Java 프로그램을 살펴보고 어떻게 작동하는지 살펴보겠습니다.

코드:

import javax.swing.JFrame;
import java.awt.*;       // AWT package is responsible for creating GUI
import javax.swing.*;    // Java swing package is responsible to provide UI components
// AWT class extents Jframe which is part of Swing package
public class AWTGraphicsSampleProgram extends JFrame {
/**
*
*/
// Defining all the static variables
private static final long serialVersionUID = 1L;
public static final int SAMPLE_CANVAS_WIDTH  = 500;
public static final int SAMPLE_CANVAS_HEIGHT = 500;
// The program enters from the main method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new AWTGraphicsSampleProgram(); // this run method will create a new object and thus invoke the constructor method.
}
});
}
//Here we are creating an instance of the drawing canvas inner class called DrawCanwas
private DrawCanvas sampleCanvas;
public AWTGraphicsSampleProgram() {
sampleCanvas = new DrawCanvas();
sampleCanvas.setPreferredSize(new Dimension(SAMPLE_CANVAS_WIDTH,            SAMPLE_CANVAS_HEIGHT));
Container containerPane = getContentPane();
containerPane.add(sampleCanvas);
setDefaultCloseOperation(EXIT_ON_CLOSE);   // setting up the default close mechanism
pack();
setTitle("......");  // set the desired title of the JFrame
setVisible(true);    // setVisible method will be set the visibility of the Jframe to true
}
/**
* here drawCanvas is the inner class of the Jpanel which is used for custom drawing
*/
private class DrawCanvas extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// Overriding paintComponent will let you to design your own painting
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
setBackground(Color.BLACK);  // setting the background color to black
graphics.setColor(Color.GREEN);  // setting up the color to green
graphics.drawLine(30, 40, 100, 200);
graphics.drawOval(150, 180, 10, 10);
graphics.drawRect(200, 210, 20, 30);
graphics.setColor(Color.magenta);
graphics.fillOval(300, 310, 30, 50);
graphics.fillRect(400, 350, 60, 50);
graphics.setColor(Color.WHITE);
graphics.setFont(new Font("Monospaced", Font.PLAIN, 12)); // setting up the font style and font size
graphics.drawString("Java Graphics in 2D ...", 10, 20);
}
}
}

출력:

Java의 2D 그래픽

그래픽 클래스는 다양한 그래픽 객체를 그리는 다양한 방법을 제공합니다. 가장 일반적인 메서드는 drawString(), drawImage() 및 fillXxx()입니다. 이러한 방법은 크게 두 가지 범주로 나눌 수 있습니다. 첫 번째 유형의 그래픽 방법은 사용자가 기본 모양, 텍스트 및 이미지를 렌더링할 수 있도록 그리기 및 채우기 기능을 제공합니다. 다른 유형의 방법은 도면이 콘솔에 나타나는 방식의 효과를 변경할 수 있는 속성 설정을 위한 것입니다. setColor 및 setFont와 같은 메소드를 사용하면 그리기 및 채우기 렌더링 방법을 결정할 수 있습니다. 그래픽 컨텍스트는 현재 글꼴의 현재 그림 색상과 같은 상태나 속성을 유지하는 역할을 담당합니다.

예시 #2

Java 2D 클래스로 무엇을 얻을 수 있는지에 대한 또 다른 예를 살펴보겠습니다.

코드:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
public class GeometricShapes extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
@SuppressWarnings("deprecation")
public GeometricShapes()
{
super( "Geometric shapes" );
setSize( 425, 160 );
show();
}
public static void main( String args[] )
{
GeometricShapes figure = new GeometricShapes();
figure.addWindowListener( new WindowAdapter()
{
public void windowclosing( WindowEvent e )
{
System.exit( 0 );
}
});
}
public void paint( Graphics graphics )
{
// Instantiating Graphics 2D class
Graphics2D graphics2D = ( Graphics2D ) graphics;
graphics2D.setPaint( new GradientPaint( 16, 30,
Color.red,
45, 105,
Color.green,
true ) );
graphics2D.fill( new Ellipse2D.Double( 6, 31, 61, 105 ) );
graphics2D.setPaint( Color.black );
graphics2D.setStroke(new BasicStroke( 9.0f ) );
graphics2D.draw( new Rectangle2D.Double( 82, 32, 67, 102 ) );
// This will create a black colored rounded rectangle
BufferedImage bufferedImage = new BufferedImage( 10, 10,                                  BufferedImage.TYPE_INT_RGB );
Graphics2D design = bufferedImage.createGraphics();
design.setColor( Color.blue );
design.fillRect( 0, 0, 9, 9 );
design.setColor( Color.orange );
design.drawRect( 2, 2, 7, 7 );
design.setColor( Color.black );
design.fillRect( 2, 2, 4, 4 );
design.setColor( Color.pink );
design.fillRect( 5, 5, 2, 2 );
graphics2D.setPaint( new TexturePaint( bufferedImage, new Rectangle( 9, 9 ) ) );
graphics2D.fill( new RoundRectangle2D.Double( 156, 31, 76, 101, 51, 51 ) );
graphics2D.setPaint( Color.CYAN );
graphics2D.setStroke(new BasicStroke( 7.0f ) );
graphics2D.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
// this will create line in red and black color
graphics2D.setPaint( Color.red );
graphics2D.draw( new Line2D.Double( 400, 40, 350, 180 ) );
float dashesArray[] = { 20 };
graphics2D.setPaint( Color.black );
graphics2D.setStroke( new BasicStroke( 4, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10, dashesArray, 0 ) );
graphics2D.draw( new Line2D.Double( 320, 30, 395, 150 ) );
}
}

출력:

Java의 2D 그래픽

예시 #3

다음 프로그램에서 2D Java를 적용해 보겠습니다.

코드:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
public class GeometricShapes2 extends JFrame
{
/**
*
*/
private static final long <em>serialVersionUID</em> = 1L;
public static void main( String args[] )
{
GeometricShapes2 design = new GeometricShapes2();
design.addWindowListener(new WindowAdapter()
{
});
}
@SuppressWarnings("deprecation")
public GeometricShapes2()
{
super( "A circle made up of stars by joining them at certain position filled with random colors" );
setBackground( Color.<em>green</em> );
setSize( 450, 450 );
show();
}
public void paint( Graphics graphics )
{
int xCoordinates[] = { 57, 69, 111, 75, 85, 57, 29, 39, 3, 45 };
int yCoordinates[] = { 2, 38, 38, 56, 98, 74, 98, 56, 38, 38 };
Graphics2D graphics2D = ( Graphics2D ) graphics;
GeneralPath starFigure = new GeneralPath();
starFigure.moveTo( xCoordinates[ 0 ], yCoordinates[ 0 ] );
for ( int j = 1; j < xCoordinates.length; j++ )
starFigure.lineTo( xCoordinates[ j ], yCoordinates[ j ] );
starFigure.closePath();
graphics2D.translate( 200, 200 );
for ( int i = 1; i <= 10; i++ )
{
graphics2D.rotate( Math.<em>PI</em> / 9.0 );
graphics2D.setColor(new Color( ( int ) ( Math.<em>random</em>() * 128 ),( int ) ( Math.<em>random</em>() * 128 ),
( int ) ( Math.<em>random</em>() * 128 ) ) );
graphics2D.fill( starFigure );
}
}
}

출력:

Java의 2D 그래픽

예시 #4

다음 프로그램에 색상 코딩을 적용해 보겠습니다.

코드:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class GeometricShapes3 extends Canvas {
/**
*
*/
private static final long serialVersionUID = 1L;
Frame windowFrame;
TextField sampleText;
Font sampleFont;
Color colorOfText;
Color colorOfCircle;
public static void main(String args[]) {
GeometricShapes3 start;
start = new GeometricShapes3();
}
public GeometricShapes3() {
this("Arial", Font.BOLD, 18, Color.gray, Color.red);
}
public GeometricShapes3(String ff, int fs, int fz, Color bg, Color fg) {
setBackground(bg);
colorOfCircle = Color.green.brighter();
colorOfText = fg;
sampleFont = new Font(ff, fs, fz);
sampleText = new TextField("eduCBA (Corporate Bridge Consultancy Pvt Ltd) ");
windowFrame = new Frame("Demo");
windowFrame.add(sampleText, BorderLayout.NORTH);
windowFrame.add(this, BorderLayout.CENTER);
windowFrame.setSize(new Dimension(300,340));
windowFrame.setLocation(150,140);
windowFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
sampleText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
repaint();
}
});
windowFrame.setVisible(true);
}
public void paint(Graphics graphics) {
String sampleTxt = sampleText.getText();
if (sampleTxt.length() == 0) return;
if (graphics instanceof Graphics2D) {
Dimension dimension = getSize();
Point point = new Point(dimension.width / 2, dimension.height / 2);
int radius = (int)(point.x * 0.84);
graphics.setColor(colorOfCircle);
graphics.drawArc(point.x - radius, point.y - radius,
radius*2-1, radius*2-1,
0, 360);
graphics.setColor(colorOfText);
graphics.setFont(sampleFont);
CircularText((Graphics2D)graphics, sampleTxt, point, radius, -Math.PI/2, 1.0);
}
else {
System.out.println("Some Error Occurred");
}
}
static void CircularText(Graphics2D graphics, String sampleTxt, Point center,
double radius, double length, double height)
{
double circleAngle = length;
Point2D circle = new Point2D.Double(center.x, center.y);
char chArray[] = sampleTxt.toCharArray();
FontMetrics fm = graphics.getFontMetrics();
AffineTransform formx, formy;
formx = AffineTransform.getTranslateInstance(circle.getX(),circle.getY());
for(int i = 0; i < chArray.length; i++) {
double cwid = (double)(getWidth(chArray[i],fm));
if (!(chArray[i] == ' ' || Character.isSpaceChar(chArray[i]))) {
cwid = (double)(fm.charWidth(chArray[i]));
formy = new AffineTransform(formx);
formy.rotate(circleAngle, 0.0, 0.0);
String chstr = new String(chArray, i, 1);
graphics.setTransform(formy);
graphics.drawString(chstr, (float)(-cwid/2), (float)(-radius));
}
if (i < (chArray.length - 1)) {
double adv = cwid/2.0 + fm.getLeading() + getWidth(chArray[i + 1],fm)/2.0;
circleAngle += Math.sin(adv / radius);
}
}
}
static int getWidth(char charText, FontMetrics fontMetrics) {
if (charText == ' ' || Character.isSpaceChar(charText)) {
return fontMetrics.charWidth('n');
}
else {
return fontMetrics.charWidth(charText);
}
}
} <strong> </strong><strong>Output:</strong>

Java의 2D 그래픽

예시 #5

텍스트 그래픽을 위한 2D Java.

코드:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
public class FontsDemo extends Frame {
/**
*
*/
private static final long <em>serialVersionUID</em> = 1L;
public static void main( String[] argv ) {
FontsDemo myExample = new FontsDemo( "Text Graphics" );
}
public FontsDemo( String title ) {
super( title );
setSize( 450, 180 );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
dispose();
System.<em>exit</em>( 0 );
}
} );
setVisible( true );
}
public void paint( Graphics g ) {
Graphics2D graphics = (Graphics2D) g;
FontRenderContext frc = graphics.getFontRenderContext();
Font font = new Font( "Arial", Font.<em>HANGING_BASELINE</em> | Font.<em>BOLD</em>, 72 );
TextLayout tl = new TextLayout( "eduCBA", font, frc );
Shape myShape = tl.getOutline( AffineTransform.<em>getTranslateInstance</em>( 50, 100 ) );
Paint myPaint = loadTextureResource( "1.gif" );
graphics.setPaint( myPaint );
graphics.fill( myShape );
}
public TexturePaint loadTextureResource( String absfilename ) {
MediaTracker tracker = new MediaTracker( this );
Image imtexture = Toolkit.getDefaultToolkit().getImage( absfilename );
tracker.addImage( imtexture, 0 );
try {
tracker.waitForID( 0 );
int width = imtexture.getWidth( this );
int height = imtexture.getHeight( this );
System.<em>out</em>.println( "width" + width + " height =" + height );
BufferedImage buffImg = new
BufferedImage( width, height, BufferedImage.<em>TYPE_INT_ARGB</em> );
Graphics g = buffImg.getGraphics();
g.drawImage( imtexture, 0, 0, this );
return new TexturePaint( buffImg, new Rectangle2D.Double( 0, 0, width, height ) );
}
catch( Exception e ) {
System.<em>out</em>.println( "Exception on Image-Texture Loading" );
}
return null;
}
}

출력:

Java의 2D 그래픽

결론

 이제 기사를 마쳤으므로 여러분이 Java 2D 그래픽으로 무엇을 얻을 수 있는지에 대한 공정한 아이디어를 가지셨기를 바랍니다. 솔직히 Java 2D 클래스의 기능은 단순한 모양과 도형에만 국한되지 않습니다. 복잡한 도형과 기하학적 모양을 디자인하도록 확장할 수 있으며 주로 기존 클래스와 방법을 어떻게 활용하느냐에 따라 달라집니다.

위 내용은 Java의 2D 그래픽의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java 종료 후크다음 기사:Java 종료 후크