Java2D介绍

掌握Java2D动画:从基础到进阶 实现自定义动画效果需要深入理解Java2D的绘图机制和动画更新机制,以下是如何利用Java2D实现自定义动画效果的步骤和实例。定义动画对象的模型:创建一个模型类来存储动画对象的状态信息,如位置、大小、颜色等。实现动画更新逻辑:在自定义的动画类中,实现方法,根据时间更新动画对象的状态。动画的同步和控制:通过监听器或定时器来控制动画的开始、暂停、结束等状态。y += dy;repaint();});@Override。 阅读详情

1.

1.1 Overview

In Java 1.2, the paintComponent method is supplied with a Graphics2D object (a subclass of Graphics), which contains a much richer set of drawing operations. It includes pen widths, dashed lines, image and gradient color fill patterns, the use of arbitrary local fonts, a floating point coordinate system, and a number of coordinate transformation operations. However, to maintain compatibility with Swing as used in Java 1.1, the declared type of the paintComponent argument is Graphics, so you have to cast it to Graphics2D before using it.

Java 1.1

 

Java 1.2

public void paint(Graphics g) {

  // Set pen parameters

  g.setColor(someColor);

  g.setFont(someLimitedFont);

  // Draw a shape

  g.drawString(...);

  g.drawLine(...)

  g.drawRect(...);     // outline

  g.fillRect(...);     // solid

  g.drawPolygon(...);  // outline

  g.fillPolygon(...);  // solid

  g.drawOval(...);     // outline

  g.fillOval(...);     // solid

  ...

}

 

public void paintComponent(Graphics g) {

  // Clear off-screen bitmap

  super.paintComponent(g);

  // Cast Graphics to Graphics2D

  Graphics2D g2d = (Graphics2D)g;

  // Set pen parameters

  g2d.setPaint(fillColorOrPattern);

  g2d.setStroke(penThicknessOrPattern);

  g2d.setComposite(someAlphaComposite);

  g2d.setFont(anyFont);

  g2d.translate(...);

  g2d.rotate(...);

  g2d.scale(...);

  g2d.shear(...);

  g2d.setTransform(someAffineTransform);

  // Allocate a shape

  SomeShape s = new SomeShape(...);

  // Draw shape

  g2d.draw(s);  // outline

  g2d.fill(s);  // solid

}

1.2 Main New Features

  • Colors and patterns: gradient fills, fill patterns from tiled images, transparency

  • Local fonts

  • Pen thicknesses, dashing patterns, and segment connection styles

  • Coordinate transformations

1.3 General Approach

  • Cast the Graphics object to a Graphics2D object

·                public void paintComponent(Graphics g) {

·                  super.paintComponent(g);  // Typical Swing approach

·                  Graphics2D g2d = (Graphics2D)g;

·                  g2d.doSomeStuff(...);

·                  ...

·                }

  • Create a Shape object

·                Rectangle2D.Double rect = ...;

·                Ellipse2D.Double ellipse = ...;

·                Polygon poly = ...;

·                GeneralPath path = ...;

·                SomeShapeYouDefined shape = ...; // Satisfies Shape interface

·                ...

  • Optional: modify drawing parameters

·                g2d.setPaint(fillColorOrPattern);

·                g2d.setStroke(penThicknessOrPattern);

·                g2d.setComposite(someAlphaComposite);

·                g2d.setFont(someFont);

·                g2d.translate(...);

·                g2d.rotate(...);

·                g2d.scale(...);

·                g2d.shear(...);

·                g2d.setTransform(someAffineTransform);

  • Draw an outlined or solid version of the Shape

·                g2d.draw(someShape);

·                g2d.fill(someShape);


2. Drawing Shapes in Java2D

2.1 Drawing Shapes: Overview

With the AWT, you generally drew a shape by calling the drawXxx or fillXxx method of the Graphics object. In Java2D, you generally create a Shape object, then call either the draw or fill method of the Graphics2D object, supplying the Shape object as an argument. For example:

public void paintComponent(Graphics g) {

  super.paintComponent(g);

  Graphics2D g2d = (Graphics2D)g;

  // Assume x, y, and diameter are instance variables

  Ellipse2D.Double circle =

    new Ellipse2D.double(x, y, diameter, diameter);

  g2d.fill(circle);

  ...

}

You can still call the drawXxx methods if you like, however. This is necessary for drawString and drawImage, and possibly convenient for draw3DRect. Several classes have similar versions that store coordinates as either double precision numbers (Xxx.Double) or single precision numbers (Xxx.Float). The idea is that single precision coordinates might be slightly faster to manipulate on some platforms.

2.2 Shape Classes

Arguments to the Graphics2D draw and fill methods must implement the Shape interface. You can create your own shapes, of course, but following are the major built-in ones. Except for Rectangle and Polygon, which are Java 1.1 holdovers, these appear in the java.awt.geom package.

  • Arc2D.Double, Arc2D.Float

  • Area (a shape built by adding/subtracting other shapes)

  • CubicCurve2D.Double, CubicCurve2D.Float

  • Ellipse2D.Double, Ellipse2D.Float

  • GeneralPath (a series of connected shapes)

  • Line2D.Double, Line2D.Float

  • Polygon

  • QuadCurve2D.Double, QuadCurve2D.Float

  • Rectangle2D.Double, Rectangle2D.Float, Rectangle

  • RoundRectangle2D.Double, RoundRectangle2D.Float

2.3 Drawing Shapes: Example Code

Download the source: ShapeExample.java, WindowUtilities.java, and ExitListener.java.

ShapeExample.java

import javax.swing.*; // For JPanel, etc.

import java.awt.*;           // For Graphics, etc.

import java.awt.geom.*;      // For Ellipse2D, etc.

 

/** An example of drawing/filling shapes with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class ShapeExample extends JPanel {

  private Ellipse2D.Double circle =

    new Ellipse2D.Double(10, 10, 350, 350);

  private Rectangle2D.Double square =

    new Rectangle2D.Double(10, 10, 350, 350);

 

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    g2d.fill(circle);

    g2d.draw(square);

  }

 

  // super.paintComponent clears offscreen pixmap,

  // since we're using double buffering by default.

 

  protected void clear(Graphics g) {

    super.paintComponent(g);

  }

 

  protected Ellipse2D.Double getCircle() {

    return(circle);

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);

  }

}

WindowUtilities.java

import javax.swing.*;

import java.awt.*;

 

/** A few utilities that simplify testing of windows in Swing.

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class WindowUtilities {

 

  /** Tell system to use native look and feel, as in previous

   *  releases. Metal (Java) LAF is the default otherwise.

   */

 

  public static void setNativeLookAndFeel() {

    try {

      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    } catch(Exception e) {

      System.out.println("Error setting native LAF: " + e);

    }

  }

 

  /** A simplified way to see a JPanel or other Container.

   *  Pops up a JFrame with specified Container as the content pane.

   */

 

  public static JFrame openInJFrame(Container content,

                                    int width,

                                    int height,

                                    String title,

                                    Color bgColor) {

    JFrame frame = new JFrame(title);

    frame.setBackground(bgColor);

    content.setBackground(bgColor);

    frame.setSize(width, height);

    frame.setContentPane(content);

    frame.addWindowListener(new ExitListener());

    frame.setVisible(true);

    return(frame);

  }

 

  /** Uses Color.white as the background color. */

 

  public static JFrame openInJFrame(Container content,

                                    int width,

                                    int height,

                                    String title) {

    return(openInJFrame(content, width, height, title, Color.white));

  }

 

  /** Uses Color.white as the background color, and the

   *  name of the Container's class as the JFrame title.

   */

 

  public static JFrame openInJFrame(Container content,

                                    int width,

                                    int height) {

    return(openInJFrame(content, width, height,

                        content.getClass().getName(),

                        Color.white));

  }

}

ExitListener.java

import java.awt.*;

import java.awt.event.*;

 

/** A listener that you attach to the top-level Frame or JFrame of

 *  your application, so quitting the frame exits the application.

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class ExitListener extends WindowAdapter {

  public void windowClosing(WindowEvent event) {

    System.exit(0);

  }

}

2.4 Drawing Shapes: Example Output


3. Paint Styles in Java2D

3.1 Paint Styles: Overview

When you fill a Shape, the current Paint attribute of the Graphics2D object is used. This can be a Color (solid color), a GradientPaint (gradient fill gradually combining two colors), a TexturePaint (tiled image), or a new version of Paint that you write yourself. Use setPaint and getPaint to change and retrieve the Paint settings. Note that setPaint and getPaint supersede the setColor and getColor methods that were used in Graphics.

3.2 Paint Classes

Arguments to the Graphics2D setPaint method (and return values of getPaint) must implement the Paint interface. Here are the major built-in Paint classes:

  • Color
    Has the same constants (Color.red, Color.yellow, etc.) as the AWT version, plus some extra constructors.

  • GradientPaint
    Constructors takes two points, two colors, and optionally a boolean flag that indicates that the color pattern should cycle. The first color is used at the first point, the second color at the second point, and points in between are colored based on how close they are to each of the points.

  • TexturePaint
    Constructor takes a BufferedImage and a Rectangle2D, maps the image to the rectangle, then tiles the rectangle. Creating a BufferedImage from a GIF or JPEG file is a pain. First load an Image normally, get its size, create a BufferedImage that size with BufferedImage.TYPE_INT_ARGB as the image type, get the BufferedImage's Graphics object via createGraphics, then draw the Image into the BufferedImage using drawImage. An example of this process is shown later.

3.3 Transparency

Transparency is not set in the Paint object, rather separately via an AlphaComposite object that is applied via setComposite. See Section 4 for details.

3.4 Gradient Fills: Example Code

Download the source: GradientPaintExample.java (plus ShapeExample.java, WindowUtilities.java, and ExitListener.java if you don't have them from the previous examples).

import java.awt.*;

 

/** An example of gradient fills with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class GradientPaintExample extends ShapeExample {

  // Red at (0,0), yellow at (175,175), changes gradually between.

  private GradientPaint gradient =

    new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,

                      true); // true means to repeat pattern

 

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    drawGradientCircle(g2d);

  }

 

  protected void drawGradientCircle(Graphics2D g2d) {

    g2d.setPaint(gradient);

    g2d.fill(getCircle());

    g2d.setPaint(Color.black);

    g2d.draw(getCircle());

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new GradientPaintExample(),

                                 380, 400);

  }

}

3.5 Gradient Fills: Example Output

3.6 Tiled Images as Fill Patterns -- Overview

To use tiled images, you create a TexturePaint object and specify its use via the setPaint method of Graphics2D, just as with solid colors and gradient fills. The TexturePaint constructor takes a BufferedImage and a Rectangle2D as arguments. The BufferedImage specifies what to draw, and the Rectangle2D specifies where the tiling starts. Creating a BufferedImage to hold custom drawing is relatively straightforward: call the BufferedImage constructor with a width, a height, and a type of BufferedImage.TYPE_INT_RGB, then call createGraphics on that to get a Graphics2D with which to draw. It is a bit harder to create one from an image file. First load an Image from an image file, then use MediaTracker to be sure it is done loading, then create an empty BufferedImage using the Image width and height, then get the Graphics2D via createGraphics, then draw the Image onto the BufferedImage. This process has been wrapped up in the getBufferedImage method of my ImageUtilities class.

Note, however, that as of JDK1.2beta4, tiled images fail when used in conjunction with rotation transformations.

3.7 Tiled Images as Fill Patterns: Example Code

Download the source: TiledImages.java and ImageUtilities.java (plus WindowUtilities.java and ExitListener.java if you don't have them from the previous examples).

TiledImages.java

import javax.swing.*;

import java.awt.*;

import java.awt.geom.*;

import java.awt.image.*;

 

/** An example of using TexturePaint to fill objects with tiled

 *  images. Uses the getBufferedImage method of ImageUtilities to

 *  load an Image from a file and turn that into a BufferedImage.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class TiledImages extends JPanel {

  private String dir = System.getProperty("user.dir");

  private String imageFile1 = dir + "/images/marty.jpg";

  private TexturePaint imagePaint1;

  private Rectangle imageRect;

  private String imageFile2 = dir + "/images/bluedrop.gif";

  private TexturePaint imagePaint2;

  private int[] xPoints = { 30, 700, 400 };

  private int[] yPoints = { 30, 30, 600 };

  private Polygon imageTriangle = new Polygon(xPoints, yPoints, 3);

 

  public TiledImages() {

    BufferedImage image =

      ImageUtilities.getBufferedImage(imageFile1, this);

    imageRect =

      new Rectangle(235, 70, image.getWidth(), image.getHeight());

    imagePaint1 =

           new TexturePaint(image, imageRect);

    image = ImageUtilities.getBufferedImage(imageFile2, this);

    imagePaint2 =

      new TexturePaint(image, new Rectangle(0, 0, 32, 32));

  }

 

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;

    g2d.setPaint(imagePaint2);

    g2d.fill(imageTriangle);

    g2d.setPaint(Color.blue);

    g2d.setStroke(new BasicStroke(5));

    g2d.draw(imageTriangle);

    g2d.setPaint(imagePaint1);

    g2d.fill(imageRect);

    g2d.setPaint(Color.black);

    g2d.draw(imageRect);

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new TiledImages(), 750, 650);

  }

}

ImageUtilities.java

import java.awt.*;

import java.awt.image.*;

 

/** A class that simplifies a few common image operations, in

 *  particular creating a BufferedImage from an image file, and

 *  using MediaTracker to wait until an image or several images are

 *  done loading.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 * 1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class ImageUtilities {

 

  /** Create Image from a file, then turn that into a BufferedImage.

   */

 

  public static BufferedImage getBufferedImage(String imageFile,

                                               Component c) {

    Image image = c.getToolkit().getImage(imageFile);

    waitForImage(image, c);

    BufferedImage bufferedImage =

      new BufferedImage(image.getWidth(c), image.getHeight(c),

                        BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = bufferedImage.createGraphics();

    g2d.drawImage(image, 0, 0, c);

    return(bufferedImage);

  }

 

  /** Take an Image associated with a file, and wait until it is

   *  done loading. Just a simple application of MediaTracker.

   *  If you are loading multiple images, don't use this

   *  consecutive times; instead use the version that takes

   *  an array of images.

   */

 

  public static boolean waitForImage(Image image, Component c) {

    MediaTracker tracker = new MediaTracker(c);

    tracker.addImage(image, 0);

    try {

      tracker.waitForAll();

    } catch(InterruptedException ie) {}

    return(!tracker.isErrorAny());

  }

 

  /** Take some Images associated with files, and wait until they

   *  are done loading. Just a simple application of MediaTracker.

   */

 

  public static boolean waitForImages(Image[] images, Component c) {

    MediaTracker tracker = new MediaTracker(c);

    for(int i=0; i<images.length; i++)

      tracker.addImage(images[i], 0);

    try {

      tracker.waitForAll();

    } catch(InterruptedException ie) {}

    return(!tracker.isErrorAny());

  }

}

3.8 Tiled Images as Fill Patterns: Example Output


4. Transparency in Java2D

4.1 Transparency: Overview

Java2D permits you to assign transparency (alpha) values to drawing operations so that the underlying graphics partially shows through when you draw shapes or images. You set transparency by creating an AlphaComposite object then passing it to the setComposite method of the Graphics2D object. You create an AlphaComposite by calling AlphaComposite.getInstance with a mixing rule designator and a transparency (or "alpha") value. There are 8 built-in mixing rules (see the AlphaComposite API for details), but the one normally used for drawing with transparency settings is AlphaComposite.SRC_OVER. Alpha values range from 0.0F (completely transparent) to 1.0F (completely opaque).

4.2 Transparency: Example Code

Download the source: TransparencyExample.java (plus WindowUtilities.java and ExitListener.java if you don't have them from the previous examples).

import javax.swing.*;

import java.awt.*;

import java.awt.geom.*;

 

/** An illustration of the use of AlphaComposite to make partially

 *  transparent drawings.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class TransparencyExample extends JPanel {

  private static int gap=10, width=60, offset=20,

                     deltaX=gap+width+offset;

  private Rectangle

    blueSquare = new Rectangle(gap+offset, gap+offset, width, width),

    redSquare = new Rectangle(gap, gap, width, width);

 

  private AlphaComposite makeComposite(float alpha) {

    int type = AlphaComposite.SRC_OVER;

    return(AlphaComposite.getInstance(type, alpha));

  }

 

  private void drawSquares(Graphics2D g2d, float alpha) {

    Composite originalComposite = g2d.getComposite();

    g2d.setPaint(Color.blue);

    g2d.fill(blueSquare);

    g2d.setComposite(makeComposite(alpha));

    g2d.setPaint(Color.red);

    g2d.fill(redSquare);

    g2d.setComposite(originalComposite);

  }

 

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;

    for(int i=0; i<11; i++) {

      drawSquares(g2d, i* 0.1F );

      g2d.translate(deltaX, 0);

    }

  }

 

  public static void main(String[] args) {

    String title = "Transparency example: alpha of the top (red) " +

                   "square ranges from 0.0 at the left to 1.0 at " +

                   "the right. Bottom (blue) square is opaque.";

    WindowUtilities.openInJFrame(new TransparencyExample(),

                                 11*deltaX + 2*gap, deltaX + 3*gap,

                                 title, Color.lightGray);

  }

}

4.3 Transparency: Example Output


5. Using Local Fonts in Java2D

5.1 Local Fonts: Overview

You can use the same logical font names as in Java 1.1, namely Serif (e.g. Times), SansSerif (e.g. Helvetica or Arial), Monospaced (e.g. Courier), Dialog, and DialogInput.

You can also use arbitrary local fonts if you first look up the entire list, which may take a few seconds. Lookup the fonts via the getAvailableFontFamilyNames or getAllFonts methods of GraphicsEnvironment. E.g.:

  GraphicsEnvironment env =

    GrapicsEnvironment.getLocalGraphicsEnvironment();

Then

  env.getAvailableFontFamilyNames();

or

  env.getAllFonts();  // Much slower!

Despite a misleading description in the API, trying to use an available local font in JDK 1.2 without first looking up the fonts as above gives the same result as asking for an unavailable font: a default font instead of the actual one. Note that getAllFonts returns an array of real Font objects that you can use like any other Font, but is much slower. If all you need to do is tell Java to make all local fonts available, always use getAvailableFontFamilyNames.

The best approach would be to loop down getAvailableFontFamilyNames, checking for your name, having several backup names to use if the first choice is not available. If you pass an unavailable family name to the Font constructor, a default font (SansSerif) will be used.

5.2 Example 1 -- Printing Out All Local Font Names

Download the source: ListFonts.java.

import java.awt.*;

 

/** Lists the names of all available fonts with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class ListFonts {

  public static void main(String[] args) {

    GraphicsEnvironment env =

      GraphicsEnvironment.getLocalGraphicsEnvironment();

    String[] fontNames = env.getAvailableFontFamilyNames();

    System.out.println("Available Fonts:");

    for(int i=0; i<fontNames.length; i++)

      System.out.println("  " + fontNames[i]);

  }

}

5.3 Example 2 -- Drawing with Local Fonts

Download the source: FontExample.java (plus GradientPaintExample.java, ShapeExample.java, WindowUtilities.java, and ExitListener.java if you don't have them from the previous examples).

import java.awt.*;

 

/** An example of using local fonts with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class FontExample extends GradientPaintExample {

  public FontExample() {

    GraphicsEnvironment env =

      GraphicsEnvironment.getLocalGraphicsEnvironment();

    env.getAvailableFontFamilyNames();

    setFont(new Font("Goudy Handtooled BT", Font.PLAIN, 100));

  }

 

  protected void drawBigString(Graphics2D g2d) {

    g2d.setPaint(Color.black);

    g2d.drawString("Java 2D", 25, 215);

  }

 

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    drawGradientCircle(g2d);

    drawBigString(g2d);

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new FontExample(), 380, 400);

  }

}

5.4 Drawing with Local Fonts: Example Output


6. Stroke Styles in Java2D

6.1 Stroke Styles: Overview

In the AWT, the drawXxx methods of Graphics resulted in solid, 1-pixel wide lines. Furthermore, drawing commands that consisted of multiple line segments (e.g. drawRect and drawPolygon) had a predefined way of joining the line segments together and terminating segments that do not join to others. Java2D gives you much more flexibility. In addition to setting the pen color or pattern (via setPaint, as discussed in the previous section), Java2D permits you to set the pen thickness and dashing pattern, and to specify the way line segments end and are joined together. You do this by creating a BasicStroke object, then telling the Graphics2D object to use it via the setStroke method.

6.2 Stroke Attributes

Arguments to setStroke must implement the Stroke interface, and the BasicStroke class is the sole builtin class that implements Stroke. Here are the BasicStroke constructors:

  • BasicStroke()
    Creates a BasicStroke with a pen width of 1.0, the default cap style of CAP_SQUARE, and the default join style of JOIN_MITER. See the following examples of pen widths and cap/join styles.

  • BasicStroke(float penWidth)
    Uses the specified pen width and the default cap/join styles (CAP_SQUARE and JOIN_MITER).

  • BasicStroke(float penWidth, int capStyle, int joinStyle)
    Uses the specified pen width, cap style, and join style. The cap style can be one of CAP_SQUARE (make a square cap that extends past the end point by half the pen width -- this is the default), CAP_BUTT (cut off segment exactly at end point -- use this one for dashed lines), or CAP_ROUND (make a circular cap centered on the end point, with a diameter of the pen width). The join style can be one of JOIN_MITER (extend outside edges of lines until they meet -- this is the default), JOIN_BEVEL (connect outside corners of outlines with straight line), or JOIN_ROUND (round off corner with circle with diameter equal to the pen width).

  • BasicStroke(float penWidth, int capStyle, int joinStyle, float miterLimit)
    Same as above but you can limit how far up the miter join can go (default is 10.0). Stay away from this.

  • BasicStroke(float penWidth, int capStyle, int joinStyle, float miterLimit, float[] dashPattern, float dashOffset)
    Lets you make dashed lines by specifying an array of opaque (entries at even array indices) and transparent (odd indices) segments. The offset, which is often 0.0, specifies where to start in the dashing pattern.

6.3 Stroke Thickness: Example Code

Download the source: StrokeThicknessExample.java (plus FontExample.java, GradientPaintExample.java, ShapeExample.java, WindowUtilities.java, and ExitListener.java if you don't have them from the previous examples).

import java.awt.*;

 

/** An example of Stroke (pen) widths with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class StrokeThicknessExample extends FontExample {

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    drawGradientCircle(g2d);

    drawBigString(g2d);

    drawThickCircleOutline(g2d);

  }

 

  protected void drawThickCircleOutline(Graphics2D g2d) {

    g2d.setPaint(Color.blue);

    g2d.setStroke(new BasicStroke(8)); // 8-pixel wide pen

    g2d.draw(getCircle());

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new StrokeThicknessExample(),

                                 380, 400);

  }

}

6.4 Stroke Thickness: Example Output

6.5 Dashed Lines: Example Code

Download the source: DashedStrokeExample.java (plus FontExample.java, GradientPaintExample.java, ShapeExample.java, WindowUtilities.java, and ExitListener.java if you don't have them from the previous examples).

import java.awt.*;

 

/** An example of dashed lines with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class DashedStrokeExample extends FontExample {

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    drawGradientCircle(g2d);

    drawBigString(g2d);

    drawDashedCircleOutline(g2d);

  }

 

  protected void drawDashedCircleOutline(Graphics2D g2d) {

    g2d.setPaint(Color.blue);

    // 30 pixel line, 10 pixel gap, 10 pixel line, 10 pixel gap

    float[] dashPattern = { 30, 10, 10, 10 };

    g2d.setStroke(new BasicStroke(8, BasicStroke.CAP_BUTT,

                                  BasicStroke.JOIN_MITER, 10,

                                  dashPattern, 0));

    g2d.draw(getCircle());

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new DashedStrokeExample(),

                                 380, 400);

  }

}

6.6 Dashed Lines: Example Output

6.7 Line Cap and Join Styles: Example Code

Download the source: LineStyles.java (plus WindowUtilities.java and ExitListener.java if you don't have them from the previous examples).

import javax.swing.*;

import java.awt.*;

import java.awt.geom.*;

 

/** An example of line cap and join styles with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class LineStyles extends JPanel {

  private GeneralPath path;

  private static int x = 30, deltaX = 150, y = 300, deltaY = 250,

                     thickness = 40;

  private Circle p1Large, p1Small, p2Large, p2Small, p3Large, p3Small;

  private int compositeType = AlphaComposite.SRC_OVER;

  private AlphaComposite transparentComposite =

    AlphaComposite.getInstance(compositeType, 0.4F );

  private int[] caps =

    { BasicStroke.CAP_SQUARE, BasicStroke.CAP_BUTT,

      BasicStroke.CAP_ROUND };

  private String[] capNames =

    { "CAP_SQUARE", "CAP_BUTT", "CAP_ROUND" };

  private int[] joins =

    { BasicStroke.JOIN_MITER, BasicStroke.JOIN_BEVEL,

      BasicStroke.JOIN_ROUND };

  private String[] joinNames =

    { "JOIN_MITER", "JOIN_BEVEL", "JOIN_ROUND" };

 

  public LineStyles() {

    path = new GeneralPath();

    path.moveTo(x, y);

    p1Large = new Circle(x, y, thickness/2);

    p1Small = new Circle(x, y, 2);

    path.lineTo(x + deltaX, y - deltaY);

    p2Large = new Circle(x + deltaX, y - deltaY, thickness/2);

    p2Small = new Circle(x + deltaX, y - deltaY, 2);

    path.lineTo(x + 2*deltaX, y);

    p3Large = new Circle(x + 2*deltaX, y, thickness/2);

    p3Small = new Circle(x + 2*deltaX, y, 2);

    setForeground(Color.blue);

    setFont(new Font("SansSerif", Font.BOLD, 20));

  }

 

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;

    g2d.setColor(Color.blue);

    for(int i=0; i>caps.length; i++) {

      BasicStroke stroke =

        new BasicStroke(thickness, caps[i], joins[i]);

      g2d.setStroke(stroke);

      g2d.draw(path);

      labelEndPoints(g2d, capNames[i], joinNames[i]);

      g2d.translate(3*x + 2*deltaX, 0);

    }

  }

 

  // Draw translucent circles to illustrate actual endpoints.

  // Include text labels to shold cap/join style.

 

  private void labelEndPoints(Graphics2D g2d,

                              String capLabel, String joinLabel) {

    Paint origPaint = g2d.getPaint();

    Composite origComposite = g2d.getComposite();

    g2d.setPaint(Color.red);

    g2d.setComposite(transparentComposite);

    g2d.fill(p1Large);

    g2d.fill(p2Large);

    g2d.fill(p3Large);

    g2d.setPaint(Color.yellow);

    g2d.setComposite(origComposite);

    g2d.fill(p1Small);

    g2d.fill(p2Small);

    g2d.fill(p3Small);

    g2d.setPaint(Color.black);

    g2d.drawString(capLabel, x + thickness - 5, y + 5);

    g2d.drawString(joinLabel, x + deltaX + thickness - 5, y - deltaY);

    g2d.setPaint(origPaint);

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new LineStyles(),

                                 9*x + 6*deltaX, y + 60);

  }

}

 

class Circle extends Ellipse2D.Double {

  public Circle(double centerX, double centerY, double radius) {

    super(centerX - radius, centerY - radius, 2.0*radius, 2.0*radius);

  }

}

6.8 Line Cap and Join Styles: Example Output


7. Coordinate Transformations in Java2D

7.1 Coordinate Transformations: Overview

Java2D allows you to easily translate, rotate, scale, or shear the coordinate system. This is very convenient: it is often much easier to move the coordinate system than to calculate new coordinates for each of your points. Besides, for some data structures like ellipses and strings there is no other way to get rotated or stretched versions. The meanings of translate, rotate, and scale are clear: to move, to spin, or to stretch/shrink evenly in the x and/or y direction. Shear means to stretch unevenly: an x shear moves points to the right based on how far they are from the y axis; a y shear moves points down based on how far they are from the x axis.

The easiest way to picture what is happening is to imagine that the person doing the drawing has a picture frame that he lays down on top of a sheet of paper. The drawer always sits at the bottom of the frame. To apply a translation, you move the frame (moving the drawer with it), and do the drawing in the new location. You then move the frame back to its original location, and what you now see is the final result. Similarly, for a rotation, you spin the frame (and the drawer), draw, then spin back to see the result. Similarly for scaling and shears; modify the frame without touching the underlying sheet of paper, draw, then reverse the process to see the final result.

An outside observer watching this process would see the frame move in the direction specified by the transformation, but see the sheet of paper stay fixed. This is illustrated in the second column in the diagram below. The dotted rectangle represents the frame, while the gray rectangle represents the sheet of paper. On the other hand, to the person doing the drawing it would appear that the sheet of paper moved in the opposite way from that specified in the transformation, but that he didn't move at all. This is illustrated in the third column in the following diagram. The first column illustrates the starting configuration, and the fourth illustrates the final result. You can download the Java source code that generated this figure: TransformExample.java generates the individual illustrations (each cell in the table), and TransformTest.java put them all together into a JTable inside a JFrame.

Figure 7-1: Visualizing Transformations

You can also perform more complex transformations (e.g. creating a mirror image by flipping around a line) by directly manipulating the underlying arrays that control the transformations. This is a bit more complicated to envision than the basic translatation, rotation, scaling, and shear transformations. The idea is that a new point (x2,y2) can be derived from an original point (x1,y1) as follows:

[ x2]   [  m 00   m 01   m 02  ] [ x1 ]   [ m00x1 + m01y1 + m02 ]

[ y2] = [  m 10   m 11   m 12  ] [ y1 ] = [ m10x1 + m11y1 + m12 ]

[ 1 ]   [   0    0    1  ] [ 1  ]   [         1         ]

Note that you can only supply six of the nine values in the transformation array (the mxx values). The bottom row is fixed at [ 0 0 1 ] to guarantee that the transformations preserve "straightness" and "parallelness" of lines. There are several ways of supplying this array to the AffineTransform constructor; see the AffineTransform API for details.

There are two basic ways to use transformations. You can create an AffineTransform object, set its parameters, and then assign that AffineTransform to the Graphics2D object via setTransform. This is your only choice if you want to do the more complex transformations permitted by setting explicit transformation matrices. Alternatively, for the basic transformations you can call translate, rotate, scale, and shear directly on the Graphics2D object.

7.2 Coordinate Translations and Rotations: Example Code

Download the source: RotationExample.java (plus StrokeThicknessExample.java, FontExample.java, GradientPaintExample.java, ShapeExample.java, WindowUtilities.java, and ExitListener.java if you don't have them from the previous examples).

import java.awt.*;

 

/** An example of coordinate translations and

 *  rotations with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class RotationExample extends StrokeThicknessExample {

  private Color[] colors = { Color.white, Color.black };

 

  public void paintComponent(Graphics g) {

    clear(g);

    Graphics2D g2d = (Graphics2D)g;

    drawGradientCircle(g2d);

    drawThickCircleOutline(g2d);

    // Move the origin to the center of the circle.

    g2d.translate(185.0, 185.0);

    for (int i=0; i<16; i++) {

      // Rotate the coordinate system around current

      // origin, which is at the center of the circle.

      g2d.rotate(Math.PI/8.0);

      g2d.setPaint(colors[i%2]);

      g2d.drawString("Java", 0, 0);

    }

  }

 

  public static void main(String[] args) {

    WindowUtilities.openInJFrame(new RotationExample(), 380, 400);

  }

}

7.3 Coordinate Translations and Rotations: Example Output

7.4 Shear Transformations

If you specify a non-zero x shear, then x values will be more and more shifted to the right the farther they are away from the y axis. For example, an x shear of 0.1 means that the x value will be shifted 10% of the distance the point is away from the y axis. Y shears are similar: points are shifted down in proportion to the distance they are away from the x axis.

7.5 Shear Transformations: Example Code

Download the source: ShearExample.java (plus WindowUtilities.java and ExitListener.java if you don't have them from the previous examples).

import javax.swing.*;

import java.awt.*;

import java.awt.geom.*;

 

/** An example of shear transformations with Java2D in Java 1.2.

 *

 *  From tutorial on learning Java2D at

 *  http://www.apl.jhu.edu/~hall/java/Java2D-Tutorial.html

 *

 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

 */

 

public class ShearExample extends JPanel {

  private static int gap=10, width=100;

  private Rectangle rect = new Rectangle(gap, gap, 100, 100);

 

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;

    for (int i=0; i<5; i++) {

      g2d.setPaint(Color.red);

      g2d.fill(rect);

      // Each new square gets 0.2 more x shear

      g2d.shear(0.2, 0.0);

      g2d.translate(2*gap + width, 0);

    }

  }

 

  public static void main(String[] args) {

    String title =

      "Shear: x shear ranges from 0.0 for the leftmost 'square' " +

      "to 0.8 for the rightmost one.";

    WindowUtilities.openInJFrame(new ShearExample(),

                                20*gap + 5*width, 5*gap + width,

                                title);

  }

}

7.6 Shear Transformations: Example Output


8. Conclusions

8.1 Requesting More Accurate Drawing: Rendering Hints

Since Java2D already does a lot of calculations compared to the old AWT, there are several optional features that the designers chose to disable by default in order to improve performance. Turning them on results in crisper drawing, especially for rotated text. For example, the JTable on envisioning transformations resulted in excessively jagged text using the default settings. The most important two settings are to turn on antialiasing (smooth jagged lines by blending colors) and to simply request the highest-quality rendering. This approach is illustrated below:

RenderingHints renderHints =

  new RenderingHints(RenderingHints.KEY_ANTIALIASING,

                     RenderingHints.VALUE_ANTIALIAS_ON);

renderHints.put(RenderingHints.KEY_RENDERING,

                RenderingHints.VALUE_RENDER_QUALITY);

...

 

public void paintComponent(Graphics g) {

  super.paintComponent(g);

  Graphics2D g2d = (Graphics2D)g;

  g2d.setRenderingHints(renderHints);

  ...

}

8.2 Summary of Using Java2D

  • Cast Graphics to Graphics2D wherever you have a Graphics object

  • Create Shape objects, then call Graphics2D's draw and fill methods with shapes as args.

  • Use setPaint to specify a solid color (Color), a gradient fill (GradientPaint), or tiled image (TexturePaint). TexturePaint requires a BufferedImage, which you can create from an image file by creating empty BufferedImage then drawing image into it.

  • Use AlphaComposite for transparency. Create one via AlphaComposite.getInstance with a type of AlphaComposite.SRC_OVER.

  • Local fonts: before using them you must call GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts() or GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(). Then supply name to Font constructor and specify font via setFont, as in Java 1.1.

  • BasicStroke lets you set pen thickness, dashing pattern, and line cap/join styles. Supply it to Graphics2D via setStroke.

  • Coordinate transforms let you move the coordinate system (e.g. the piece of paper you're drawing on) rather than changing what you draw. Do simple transforms via the translate, rotate, scale, and shear methods of Graphics2D. Do more complex transforms by supplying transformation matrix to AffineTransform constructor, then calling Graphics2D's setTransform method.

  • Improve drawing quality or enable antialiasing through use of rendering hints.

2. Android_逆向的历史与发展 学完本节,希望你能够:了解 Android 逆向工程的发展历程,从早期 APK 破解到现代应用保护;入门先把这几类「在干啥」搞清楚,后面学脱壳、反反调试会顺很多。(反编译 APK 得到的类汇编代码,相当于程序的「菜谱」)就能绕过验证,到后来混淆、加固、反调试一起上,逆向难度越来越高。(第三节 什么是 CPU 指令集),帮你搞清楚「反汇编看到的那些指令」是从哪来的、和 Android 逆向有啥关系。有必要——先搞清「没加固时怎么玩」,再学脱壳和对抗,思路才顺。读起来费劲,但逻辑还在,耐心一点还能跟。 阅读详情

相关推荐

Python爬虫实战:如何优雅地处理BOSS直聘的反爬机制与Cookie失效问题

本文详细介绍了如何通过Python爬虫技术优雅应对BOSS直聘的反爬机制与Cookie失效问题。从多账号轮换、动态请求头生成到代理IP管理,提供了一套完整的解决方案,帮助开发者构建稳定高效的数据采集系统,有效提升爬虫成功率与数据质量。

weixin_30733003的博客 1562

【JAVA】Graphics2D实现图片的裁剪、旋转、翻转

2、将原图中的点(dataX,dataY),点(dataX+cropWidth,dataY+cropHeight)形成的矩形, drawImage到区域A中。1、有一块长200宽100的画布,在画布的点(dx1,dy1),点(dx2,dy2)形成的矩形区域A。指以图片中心点(125,62.5)也就是图片中心,顺时针旋转5度。指以坐标点(0,0)也就是左上角,顺时针旋转5度。以一张250x125的图片为例。

想和派大星一样 1513

Linux yum源配置以及yum命令讲解

前面为大家介绍了RPM二进制包安装软件,RPM包安装的最大的缺点也提到过,就是依赖性太强,一旦遇到依赖问题,则需要我们手动解决包之间具有依赖性的问题,今天为大家介绍一种可自动解决包之间依赖关系的安装方式:yum。 yum 全称“Yellow dog Updater, Modified”,是一个专门为了解决包的依赖关系而存在的软件包管理器。就好像 Windows 系统上我们通常可以通过各种软件管家实现软件的一键安装、升级和卸载,yum就是Linux 系统中的一键安装工具。yum 解决依赖关系的基本逻辑是:yu

九派Linux的博客 2283

Java Graphics2D类的绘图方法

Java语言在Graphics类提供绘制各种基本的几何图形的基础上,扩展Graphics类提供一个Graphics2D类,它拥用更强大的二维图形处理能力,提供、坐标转换、颜色管理以及文字布局等更精确的控制。 绘图属性 Graphics2D定义了几种方法,用于添加或改变图形的状态属性。可以通过设定和修改状态属性,指定画笔宽度和画笔的连接方式;设定平移、旋转、缩放或修剪变换图形;以及设定填充图形的

Phenixfate的专栏 3073

CANoe进阶实战(第十一章)-LIN节点测试调度

《CANoe快速入门实战:LIN节点调度开发》摘要 本文是CANoe系列教程的第十一章,重点讲解如何通过CAPL编程实现LIN报文的灵活调度控制。文章采用"输入-输出-过程"三步骤法,详细介绍了调度表函数linChangeSchedTable()、启动/停止函数linStartScheduler()/linStopDisturbance()等关键API的使用方法。作者创新性地通过系统变量在Test节点间接控制Network节点的调度功能,并提供了完整的节点代码实现方案。最后的Trace窗

weixin_53605885的博客 1022

[仿真实战]FDTD Solutions 8.0:从零搭建薄膜光谱分析模型

本文提供了一份基于FDTD Solutions 8.0的薄膜光谱分析模型从零搭建实战指南。通过详细步骤,手把手教你创建玻璃基底与硅薄膜的几何结构、设置仿真区域与边界条件、配置光源与监视器,并最终计算反射率与透射率光谱。内容涵盖参数扫描与优化,旨在帮助用户快速掌握FDTD仿真在纳米光子学与薄膜光学设计中的核心应用。

defi6farmer的博客 500

Java——图形程序设计3之利用Graphics绘制图形和绘制g2d图型

//绘制曲线 package assignment2; import java.awt.*; import javax.swing.*; public class DrawingGraphics extends JFrame{ public DrawingGraphics(){ super("Drawing curve of the function")...

点滴 2546

基于STM32设计的水质检测系统_333

水质安全对生态环境、农业生产、工业制造以及人类健康至关重要。针对传统水质检测方式检测周期长、成本高、实时性差的问题,本项目设计并实现了一种基于STM32的水质检测系统。系统采用STM32F103RCT6作为主控芯片,集成水温、pH值、电导率和浊度等传感器,能够实时采集水质数据,并通过OLED显示屏进行本地显示。同时,利用Air724UG 4G模块通过MQTT协议将数据上传至华为云IoT平台,实现远程监测。用户可通过Qt5开发的Android手机APP和Windows上位机查看水质数据,并接收超限报警提示。此

713

java 绘图

参数chars是字符数组,offset是开始绘制的偏移量,length是绘制的字符数,x和y是文本的左上角坐标。默认情况下,Graphics类使用的画笔属性是粗细为1个像素的正方形,而Graphics2D类可以调用setStroke()方法设置画笔的属性,如改变线条的粗细、虚实,定义线段端点的形状,风格等。参数str是要绘制的文本,x和y是文本的左上角坐标。//设置窗体关闭模式。使用Color类可以创建任意颜色的对象,不用担心平台是否支持该颜色,因为Java是以跨平台和与硬件无关的方式支持对颜色的管理。

2301_76593806的博客 175

Yocto开发讲解系列 - 总目录

Yocto开发讲解系列总纲Yocto开发专栏前言

fulinux的博客 3万+

SAP UI5 SimpleForm 的本质、布局选择与工程化用法:从 API 到 Fiori 规范的完整解析

SimpleForm的价值在于让开发者以“语义顺序”来思考表单:分组—行—字段,由此把更多精力放在表单信息架构与Fiori规范的落地上。当你理解了开分组、Label开新行、的断点与比例、的对齐特性、editable与的真实含义,就能据此为每个页面挑选合适的布局与参数,构建既合规又具备高可读性的企业级表单。新分组、Label新行、其他控件归当前行。SAP的断点、比例与的要点来自Fiori设计文档。SAP的适用性来自样例与课程的推荐,列表类控件不应作为其行内容。某些旧属性仅在生效,应避免误用。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 301

Java实现图像处理

在Java中,图片处理可以通过java.awt和库来完成,java.awt是 Java 标准库(Java Standard Edition, JSE)的一部分。

培根芝士的专栏 562

2026华为OD面试手撕代码真题目录

一般面试的时候每一轮技术面都会出一到两个手撕代码题,这些题的特点就是,非常短小,易于理解。不可能会再出阅读理解一样的机试题的。但是这些题目也非常注意基本功,很注意细节的处理,一般都是easy+medium题目。但是大家一定要注意,因为大部分面试官上面一开始就会让你做题,直接看你所有的做题过程(防止有人水平一般,机试就网上找的答案的蒙混过关),手撕代码题会给你后面的面试定一个基调。

MISAYAONE的博客 9万+

用Java3D或Java2D制作一个动画

利用Java3D或Java2D制作动画 在计算机图形学中,动画是一种常用的表现形式。Java提供了Java2D和Java3D两个api,可以用于创建各种动画效果。在这篇文章中,我们将通过代码示例展示如何使用Java2D绘制一个简单的动画,并在文章中展示饼状图和旅行图以增加可视化效果。 Java2D动画示例 Java2D是一...

weixin_40223484的博客 180

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

java2d 引

如何实现"java2d 引" 1. 整体流程 在实现"java2d 引"的过程中,主要包括创建一个窗口、绘制图形和添加交互事件三个步骤。具体流程如下表所示: 步骤 操作 1 创建一个 JFrame 窗口 2 在窗口中绘制图形 3 添加鼠标事件监听器 2. 操作步骤及代码示例 步骤 1:创建一个 ...

weixin_42463199的博客 96

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Java2D图形绘制

图形处理类J2SE提供了一组应用程序接口(API),用于处理2D图形,主要功能如下:(1)绘制和填充简单及复杂的形状(2)裁剪、合成图形及透明度(3)对图形进行各种几何变换(4)对高级字体进行处理并对字符串进行格式化Java2D API中对图形处理的类:1.Graphics类2.Graphics2D类3.Shape类(抽象类)绘制几何图形 - 线段Java2D支持对图形的绘制,包括绘制线段,矩形,...

Canon_M的博客 4441

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

java api练习_java2d常用api练习

package java2d;import java.awt.BasicStroke;import java.awt.Color;import java.awt.GradientPaint;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.geom.Rectangle2D;import javax.swing.J...

weixin_30563851的博客 231

Java2D特效 文字旋转

将图形围绕某点按照给定的角度进行旋转 import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing

ycb1689的专栏 2120

Java2D基本用法

Java2D基本用法简单罗列 [code="java"] 对外接口: public void CreateImage(OutputStream out,int width,int height) throws Exception { BufferedImage readImage = new BufferedImage(width, height, BufferedImage...

アイモ 399

Java2d画直角坐标系

最近项目用到java作图,首先想到的是利用开源插件jfreechart,文档收费,网上资料参差不齐,最后还是觉得采用java2D bufferedImage作图。 现在分享一下。 把一张图片分为border部分和主体部分,如下图所示: 定义一个边界类 /** * Copyright (c) 2014, alax * All Rights Reserved. */ packag

8720

java 2d pdf_java2D图形绘制.pdf

第三讲 Java2D图形绘制基础内容提要• Java2D 概述• 矢量图编程• 位图编程• 绘制几何图形• 填充图形• 图形变换1 Java2D 概述• Java 提供的一组API,用于处理2D图形及图像功能:• 绘制和填充简单及复杂的形状• 裁剪、合成和透明度• 图像处理和变换• 高级字体处理和字符串格式化• Java系统及应用程序是如何实现图形功能的呢?首先,Java系统在AW...

weixin_39737951的博客 228

Learn Java2D

如果能够在无聊的时候,静下心来学习学习,总是会有收获的。可惜,年纪大了,心却还是没法静下来。最近,看了看 2D 方面的一些文档、代码,对2D有了一些基础的认识。比较好的Java2D的教材:http://java.sun.com/...

cuanqia2118的博客 128

JAVA2D Shape 高级

除了内置的形状类的能力之外,Java 2D 还具有通过组合 Shape 对象来构造复杂形状的能力。这一功能称为构造型区域几何 或 CAG。Shape 接口的特殊实现,即 java.awt.geom.Area 类,在 Shape 类上执行各种二进制操作。有四种组合操作:add():组合两个形状。它不必有任何共同区域。subtract():除去指定区域。intersect():

浮白 5380

使用Java2D绘图——jsp中的验证码

那天突然看到了一些中文的验证码,所以想写一些东西,帮助大家了解一下在jsp页面中如何生成自己的验证码 一、简介 在 Java 2 平台之前,语言中的图形功能相当简单,仅限于单像素厚度的实线;少数几个几何图形(如椭圆、弧和多边形);和基本的画图功能。随着 Java 2D API(它包含一个真正的功能集)的出现,所有的一切都改变了。 Java 2D API是JFC (Java Fun

xuenandong的专栏 720

java2d_创建Java2D图形 | 学步园

创建Java2D图形下面我们将介绍如何将Swing容器(存放GUI组件的纯黑色面板和框架)变成一块可以在上面绘制字体、颜色、形状和图形的艺术画布。1、使用Font类在Java中,颜色和字体使用java.awt包中的Color和Font类来表示。字体使用构造函数Font(String , int , int)来创建,3个参数分别为:>字体的名字,它可以使描述性名字,也可以是实际的字体名;&gt...

weixin_32687875的博客 420

创建Java2D图形

创建Java2D图形        下面我们将介绍如何将Swing容器(存放GUI组件的纯黑色面板和框架)变成一块可以在上面绘制字体、颜色、形状和图形的艺术画布。 1、使用Font类        在Java中,颜色和字体使用java.awt包中的Color和Font类来表示。字体使用构造函数Font(String , int , int)来创建,3个参数分别为:

低调、博学、修身 1406
上一篇: 中文乱码问题
下一篇: curve代码
lanjun2005
博客等级 码龄21年 0粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值