如何沿路径java2d绘制阿拉伯语或希伯来语文本

时间:2017-04-11 12:21:33

标签: java

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

感谢。

1 个答案:

答案 0 :(得分:1)

首先确保您的Java代码以UTF-8保存 enter image description here

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

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,);

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

Full working code:

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);
  }
}