Swing/TransformedShape のバックアップの現在との差分(No.9)
- category: swing folder: TransformedShape title: Fontを回転する tags: [Font, Shape, TextLayout, Animation, AffineTransform] author: aterai pubdate: 2006-10-30T12:57:51+09:00 description: 文字のアウトラインを取得して、これを回転してみます。 description: Fontから文字のアウトラインを取得し、その中心をアンカーポイントに設定して回転します。 image:
概要
文字のアウトラインを取得して、これを回転してみます。概要
Font
から文字のアウトラインを取得し、その中心をアンカーポイントに設定して回転します。
Screenshot
Advertisement
サンプルコード
サンプルコード
class FontRotateAnimation extends JComponent implements ActionListener {
private final javax.swing.Timer animator;
private final Timer animator;
private int rotate;
private final Shape shape;
private Shape s;
#spanadd
#spanend
public FontRotateAnimation(String str) {
super();
animator = new javax.swing.Timer(5, this);
animator = new Timer(10, this);
addHierarchyListener(new HierarchyListener() {
@Override public void hierarchyChanged(HierarchyEvent e) {
JComponent c = (JComponent)e.getSource();
if((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED)!=0 &&
animator!=null && !c.isDisplayable()) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0
&& animator != null && !e.getComponent().isDisplayable()) {
animator.stop();
}
}
});
Font font = new Font(Font.SERIF, Font.PLAIN, 200);
FontRenderContext frc = new FontRenderContext(null, true, true);
shape = new TextLayout(str, font, frc).getOutline(null);
s = shape;
animator.start();
}
@Override public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
#spanadd
#spanend
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.BLACK);
g2.fill(s);
g2.dispose();
}
#spanadd
#spanend
@Override public void actionPerformed(ActionEvent e) {
repaint(s.getBounds());
Rectangle2D b = shape.getBounds();
Point2D.Double p = new Point2D.Double(
b.getX() + b.getWidth()/2d, b.getY() + b.getHeight()/2d);
Rectangle2D b = shape.getBounds2D();
Point2D p = new Point2D.Double(
b.getX() + b.getWidth() / 2d, b.getY() + b.getHeight() / 2d);
AffineTransform at = AffineTransform.getRotateInstance(
Math.toRadians(rotate), p.getX(), p.getY());
AffineTransform toCenterAT = AffineTransform.getTranslateInstance(
getWidth()/2d - p.getX(), getHeight()/2d - p.getY());
getWidth() / 2d - p.getX(), getHeight() / 2d - p.getY());
Shape s1 = at.createTransformedShape(shape);
s = toCenterAT.createTransformedShape(s1);
repaint(s.getBounds());
rotate = (rotate>=360) ? 0 : rotate+2;
rotate = rotate >= 360 ? 0 : rotate + 2;
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、TextLayout
から文字列のアウトラインをShape
として取得しています。
解説
上記のサンプルでは、対象文字、Font
、FontRenderContext
からTextLayout
を生成し、TextLayout#getOutline()
メソッドで文字のアウトラインをShape
として取得しています。
コメント
- -
-
OpenJDK Corretto-8.212
で実行すると回転中にフォント表示が乱れる件は、Java2D rendering may break when using soft clipping effects · Issue #127 · corretto/corretto-8、8u222
で修正済みされる予定