Java Tutorial/2D Graphics/TextLayout

Материал из Java эксперт
Перейти к: навигация, поиск

Drawing a Paragraph of Text

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BasicShapes extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    drawParagraph(g2d, "adfasdfaf", 20);
  }
  void drawParagraph(Graphics2D g, String paragraph, float width) {
    LineBreakMeasurer linebreaker = new LineBreakMeasurer(new AttributedString(paragraph)
        .getIterator(), g.getFontRenderContext());
    float y = 0.0f;
    while (linebreaker.getPosition() < paragraph.length()) {
      TextLayout tl = linebreaker.nextLayout(width);
      y += tl.getAscent();
      tl.draw(g, 0, y);
      y += tl.getDescent() + tl.getLeading();
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Basic Shapes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new BasicShapes());
    frame.setSize(350, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Drawing Text with Mixed Styles

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BasicShapes extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    int x = 10, y = 10, start = 2, end = 4;
    AttributedString astr = new AttributedString("aString");
    astr.addAttribute(TextAttribute.FONT, new Font("", 1, 1), start, end);
    astr.addAttribute(TextAttribute.BACKGROUND, Color.red, start, end);
    // Draw mixed-style text
    TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());
    tl.draw(g2d, x, y);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Basic Shapes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new BasicShapes());
    frame.setSize(350, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Draw text with TextLayout

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
  public Main() {
    setBackground(Color.white);
  }
  public void paint(Graphics g) {
    Graphics2D g2D;
    g2D = (Graphics2D) g;
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    FontRenderContext frc = g2D.getFontRenderContext();
    Font font1 = new Font("Courier", Font.BOLD, 24);
    String str1 = new String("Java");
    TextLayout tl = new TextLayout(str1, font1, frc);
    g2D.setColor(Color.gray);
    tl.draw(g2D, 50, 150);
  }
  public static void main(String s[]) {
    JFrame frame1 = new JFrame("2D Text");
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.getContentPane().add("Center", new Main());
    frame1.pack();
    frame1.setSize(new Dimension(500, 300));
    frame1.setVisible(true);
  }
}





Getting the Shape from the Outline of Text

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BasicShapes extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    getTextShape(g2d, "asdf", new Font("", 1, 1));
  }
  public Shape getTextShape(Graphics2D g2d, String str, Font font) {
    FontRenderContext frc = g2d.getFontRenderContext();
    TextLayout tl = new TextLayout(str, font, frc);
    return tl.getOutline(null);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Basic Shapes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new BasicShapes());
    frame.setSize(350, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Make your own animation from a series of images

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JPanel implements ActionListener {
  ImageIcon images[];
  int totalImages = 30, currentImage = 0, animationDelay = 50;
  Timer animationTimer;
  public Main() {
    images = new ImageIcon[totalImages];
    for (int i = 0; i < images.length; ++i)
      images[i] = new ImageIcon("images/java" + i + ".gif");
    startAnimation();
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (images[currentImage].getImageLoadStatus() == MediaTracker.ruPLETE) {
      images[currentImage].paintIcon(this, g, 0, 0);
      currentImage = (currentImage + 1) % totalImages;
    }
  }
  public void actionPerformed(ActionEvent e) {
    repaint();
  }
  public void startAnimation() {
    if (animationTimer == null) {
      currentImage = 0;
      animationTimer = new Timer(animationDelay, this);
      animationTimer.start();
    } else if (!animationTimer.isRunning())
      animationTimer.restart();
  }
  public void stopAnimation() {
    animationTimer.stop();
  }
  public static void main(String args[]) {
    Main anim = new Main();
    JFrame app = new JFrame("Animator test");
    app.add(anim, BorderLayout.CENTER);
    app.setSize(300,300);
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.setSize(anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30);
  }
}





Styled Text

import java.awt.Canvas;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import javax.swing.JFrame;
public class Draw2DTextLayout extends JFrame {
  public static void main(String args[]) {
    Draw2DTextLayout app = new Draw2DTextLayout();
  }
  public Draw2DTextLayout() {
    add("Center", new MyCanvas());
    setSize(400, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  }
  class MyCanvas extends Canvas {
    public void paint(Graphics graphics) {
      Graphics2D g = (Graphics2D) graphics;
      FontRenderContext frc = g.getFontRenderContext();
      TextLayout[] s = new TextLayout[3];
      Font f1 = new Font("Helvetica", Font.BOLD, 24);
      Font f2 = new Font("TimesRoman", Font.ITALIC, 14);
      Font f3 = new Font("Helvetica", Font.PLAIN, 12);
      s[0] = new TextLayout("This is the first sentence.", f1, frc);
      s[1] = new TextLayout("This is the second sentence.", f2, frc);
      s[2] = new TextLayout("This is the third sentence.", f3, frc);
      int yOffset = 0;
      for (int i = 0; i < s.length; ++i) {
        s[i].draw(g, 100, 100 + yOffset);
        yOffset += s[i].getAscent() + s[i].getDescent() + s[i].getLeading();
      }
    }
  }
}





Text Layout with mouse clicking and selecting action

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.font.FontRenderContext;
import java.awt.font.TextHitInfo;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextLayoutWithMouseClickDrag{
  public static void main(String arg[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add("Center", new DisplayPanel());
    frame.pack();
    frame.setSize(new Dimension(400, 300));
    frame.setVisible(true);
  }
}
class DisplayPanel extends JPanel {
  FontRenderContext frc = new FontRenderContext(null, false, false);
  Font font = new Font("Arial", Font.PLAIN, 36);
  Rectangle2D rect;
  float rx, ry, rw, rh;
  TextHitInfo hitInfo;
  Color caretColor;
  int hit1, hit2;
  int w=400, h=200;
  TextLayout layout = new TextLayout("j a v a 2 s . c o m", font, frc);
  public DisplayPanel() {
    setSize(400, 200);
    addMouseListener(new MouseHandler());
    addMouseMotionListener(new MouseMotionHandler());
    rx = (float) (w / 2 - layout.getBounds().getWidth() / 2);
    ry = (float) 3 * h / 4;
    rw = (float) (layout.getBounds().getWidth());
    rh = (float) (layout.getBounds().getHeight());
    rect = new Rectangle2D.Float(rx, ry, rw, rh);
  }
  public void update(Graphics g) {
    g.clearRect(0, 0, getWidth(), getHeight());
    paintComponent(g);
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    AffineTransform at = AffineTransform.getTranslateInstance(rx, ry);
    Shape hilight = layout.getLogicalHighlightShape(hit1, hit2);
    hilight = at.createTransformedShape(hilight);
    g2.setColor(Color.lightGray);
    g2.fill(hilight);
    g2.setColor(Color.black);
    layout.draw(g2, rx, ry);
    Shape[] caretShapes = layout.getCaretShapes(hit1);
    Shape caret = at.createTransformedShape(caretShapes[0]);
    g2.setColor(caretColor);
    g2.draw(caret);
  }
  public int getHitLocation(int mouseX, int mouseY) {
    hitInfo = layout.hitTestChar(mouseX, mouseY, rect);
    return hitInfo.getInsertionIndex();
  }
  class MouseHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent e) {
      caretColor = getForeground();
      hit1 = getHitLocation(e.getX(), e.getY());
      hit2 = hit1;
      repaint();
    }
    public void mousePressed(MouseEvent e) {
      caretColor = getForeground();
      hit1 = getHitLocation(e.getX(), e.getY());
      hit2 = hit1;
      repaint();
    }
    public void mouseReleased(MouseEvent e) {
      hit2 = getHitLocation(e.getX(), e.getY());
      repaint();
    }
  }
  class MouseMotionHandler extends MouseMotionAdapter {
    public void mouseDragged(MouseEvent e) {
      caretColor = getBackground();
      hit2 = getHitLocation(e.getX(), e.getY());
      repaint();
    }
  }
}