有人举过一个例子,说明如何沿java2d中的路径绘制阿拉伯或希伯来文字吗?
我看这个例子http://www.java2s.com/Code/Java/2D-Graphics-GUI/Drawtextalongacurve.htm,但是当我用阿拉伯语或希伯来语文字尝试时,它不起作用。我有镜面效果。

谢谢。

最佳答案

首先确保您的Java代码保存在UTF-8中
java - 如何沿着路径java2d绘制阿拉伯或希伯来文字-LMLPHP

然后一种简单的解决方案是像这样反转文本:

String s = (new StringBuffer("מה הבעיה אחי?")).reverse().toString();


但这会导致特殊字符(例如(,{,>)

正确的方法是使用layoutGlyphVector方法
给它Font.LAYOUT_RIGHT_TO_LEFT标志:

GlyphVector gv = font.layoutGlyphVector(g2.getFontRenderContext(), s.toCharArray(), 0, s.length(), Font.LAYOUT_RIGHT_TO_LEFT);


代替

 GlyphVector gv = font.createGlyphVector(frc, s,);


然后您的文本将正确布局:

java - 如何沿着路径java2d绘制阿拉伯或希伯来文字-LMLPHP

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class RollingText extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    String s = "מה הבעיה אחי?";
    Font font = new Font("LucidaSans", Font.PLAIN, 24);
    FontRenderContext frc = g2.getFontRenderContext();
    g2.translate(40, 80);

    GlyphVector gv = font.layoutGlyphVector(g2.getFontRenderContext(), s.toCharArray(), 0, s.length(), Font.LAYOUT_RIGHT_TO_LEFT);

    int length = gv.getNumGlyphs();
    for (int i = 0; i < length; i++) {
      Point2D p = gv.getGlyphPosition(i);
      double theta = (double) i / (double) (length - 1) * Math.PI / 4;
      AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
      at.rotate(theta);
      Shape glyph = gv.getGlyphOutline(i);
      Shape transformedGlyph = at.createTransformedShape(glyph);
      g2.fill(transformedGlyph);
    }
  }

  public static void main(String[] args) {
    JFrame f = new JFrame("RollingText v1.0");
    f.getContentPane().add(new RollingText());
    f.setSize(600, 300);
    f.setVisible(true);
  }
}

09-28 10:10