Java 中的 2D 图形
借助 Java 2 平台的一些高级功能,可以使用 Java 编程来实现 2D 图形,其中包括用于图像处理、高级图形设计选项、几何变换、Alpha 合成等操作的 Java 内置函数java 2D包下提供了许多包,例如awt、awt.image、awt.color、awt.font、awt.geom、awt.print和awt.image.renderable。 Java 因其高质量的图形结果而成为游戏开发人员社区中著名的首选选项,各种各样的几何设计选项有利于文档的打印,并允许保持所开发产品的性能。
广告 该类别中的热门课程 JAVA 掌握 - 专业化 | 78 课程系列 | 15 次模拟测试Java 2D 渲染
Java 2D API 支持跨所有不同设备的统一渲染模型:显示监视器或打印机。在程序开发过程中,无论最终组件是打印机还是显示器,渲染都以相同的方式工作。该包根据最终组件自动检测并更改图形上下文。 Java 2D API 由 java.awt.Graphics2D 组成,它扩展了 Graphics 类以提供对增强图形和渲染功能的支持。
以下是该软件包提供的功能:
- 支持原始几何形状和图形的渲染。
- 它提供了使用描边用绘画属性中指定的任何颜色或图案填充任何形状内部的选项。
- 它可以让您渲染指定的图像。
- 它可以让您将文本字符串转换为字形,并用绘制属性中指定的颜色填充。
示例#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); } } }
输出:
Graphics类提供了不同的方法来绘制不同的图形对象。最常见的方法是drawString()、drawImage() 和fillXxx()。这些方法大致可分为两类。第一种类型的 Graphics 方法是,它提供绘制和填充功能,使用户能够渲染基本形状、文本和图像。另一种类型的方法是属性设置,它允许您更改绘图在控制台中的显示效果。 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 ) ); } }
输出:
示例 #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 ); } } }
输出:
示例#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>
示例#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 图形的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
