2014-05-20 6 views
0

현재 롤링 텍스트 메서드를 만들려고합니다.이 메서드는 인수로 String을 사용합니다. 곧, 왼쪽에서 오른쪽으로 그리기 시작하고 시간이 지남에 따라 새로운 행으로 넘어 가서 화면에서 벗어나지 않습니다. 내 목표를 달성하기 위해 FontMetrics을 사용하고 있습니다.Java : 그래픽 정렬 문자열

내 주 클래스의 렌더링 메서드에서 내 RollingText.render(Graphics g, int x, int y)에 인수를 전달합니다. 내 render 메서드 내에서 Graphics 글꼴 및 색상을 설정하고 모두 FontMetrics을 잡아서 FontMetrics에서 다른 물건을 잡기 시작합니다. 또한 문자열을 텍스트로 그리기위한 for 루프를 사용합니다.

public void render(Graphics g, int x, int y) { 
    // text is the field that a grab the index of the string from 
    // the index is the max part of the string I'm grabbing from, 
    // increments using the update() method 
    String str = text.substring(0, index); 
    String[] words = str.split(" "); 

    Font f = new Font(g.getFont().getName(), 0, 24); 
    FontMetrics fmetrics = g.getFontMetrics(f); 
    g.setColor(Color.white); 
    g.setFont(f); 

    int line = 1; 
    int charsDrawn = 0; 
    int wordsDrawn = 0; 
    int charWidth = fmetrics.charWidth('a'); 
    int fontHeight = fmetrics.getHeight(); 
    for (int i = 0; i < words.length; i++) { 
     int wordWidth = fmetrics.stringWidth(words[i]); 
     if (wordWidth* wordsDrawn + charWidth * charsDrawn > game.getWidth()) { 
      line++; 
      charsDrawn = 0; 
      wordsDrawn = 0; 
     } 

     g.drawString(words[i], x * charsDrawn + charWidth, y + fontHeight * line); 

     charsDrawn += words[i].length(); 
     wordsDrawn += 1; 
    } 
} 

현재이 시점에서 모든 것이 잘 작동하지만 남은 문제는 drawString 방법의 각 단어 사이의 공간은 크게 과장과 같이이다이다 :

Rolling Text Demo

라인 :

g.drawString(words[i], x * charsDrawn + charWidth, y + fontHeight * line); 

나는 현재의 X 멋 부리다에 대한 계산을 수행하는 올바른 방법을 찾는 데 유일한 문제 이온. 현재, 그것은 단어의 길이에 따라 무겁고 역동적 인 간격을 가지고 있으며, 적어도 정상적으로 보이게하는 방법을 알 수는 없습니다. 나는 현재 정의 된 정수와 다른 조합을 시도했다. 발생하는 문제는 부정확 한 간격에서 벗어나는 것, 위치 지정 및 깜박임을 줄이는 것, 함께 실행되는 텍스트 일 ​​것입니다.

마지막으로, 내 질문은 어떤 알고리즘을 사용하여 텍스트의 x 좌표가 올바르게 보이게 할 수 있습니까?

답변

1

다양한 변수를 기반으로 x/y 위치를 계산하려는 이유가 확실하지 않습니다. 단순히 x/y 값에 FontMetrics#stringWidth 또는 FontMetrics#getHeight을 추가하면 더 간단해질 것입니다.

또한 FontMetrics#stringWidth을 사용하고 "샘플"너비를 기준으로 개별 문자의 너비를 계산하는 것으로 전환되는 것 같습니다 ... , 이것은 계산을 간단하게 ... 혼란스럽게합니다. 또한 우선 순위 문제가있는 것으로 보입니다.

x * charsDrawn + charWidthx + (charsDrawn * charWidth)일까요?

실제로 대신, 결과를 재현하기 위해 예제 코드를 얻을 수 없었습니다

, 나는이

TextLayout

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.FontMetrics; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class RenderText { 

    public static void main(String[] args) { 
     new RenderText(); 
    } 

    public RenderText() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private String text; 
     private int index; 

     public TestPane() { 
      text = "A long time ago, in a galaxy far, far, away..." 
        + "A vast sea of stars serves as the backdrop for the main title. " 
        + "War drums echo through the heavens as a rollup slowly crawls " 
        + "into infinity." 
        + "  It is a period of civil war. Rebel spaceships, " 
        + "  striking from a hidden base, have won their first " 
        + "  victory against the evil Galactic Empire." 
        + "  During the battle, Rebel spies managed to steal " 
        + "  secret plans to the Empire's ultimate weapon, the " 
        + "  Death Star, an armored space station with enough " 
        + "  power to destroy an entire planet." 
        + "  Pursued by the Empire's sinister agents, Princess " 
        + "  Leia races home aboard her starship, custodian of " 
        + "  the stolen plans that can save her people and " 
        + "  restore freedom to the galaxy..."; 

      index = text.length() - 1; 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      render(g, 0, 0); 
      g2d.dispose(); 
     } 

     public void render(Graphics g, int x, int y) { 
      // text is the field that a grab the index of the string from 
      // the index is the max part of the string I'm grabbing from, 
      // increments using the update() method 
      String str = text.substring(0, index); 
      String[] words = str.split(" "); 

      Font f = new Font(g.getFont().getName(), 0, 24); 
      FontMetrics fmetrics = g.getFontMetrics(f); 
//   g.setColor(Color.white); 
      g.setFont(f); 

      int fontHeight = fmetrics.getHeight(); 

      int spaceWidth = fmetrics.stringWidth(" "); 

      int xPos = x; 
      int yPos = y; 
      for (String word : words) { 
       int wordWidth = fmetrics.stringWidth(word); 
       if (wordWidth + xPos > getWidth()) { 
        yPos += fontHeight; 
        xPos = x; 
       } 
       g.drawString(word, x + xPos, yPos + fmetrics.getAscent()); 
       xPos += wordWidth + spaceWidth; 
      } 
     } 
    } 

} 

당신이 실제 runnable example that demonstrates your problem를 제공 할 수 있습니다 때까지 ... 그것을 단순화 내가 할 수있는 최선이다 ...