Java-da tasvirga o'ralgan matnni qanday ko'rsatishim mumkin

Java-dan foydalanib, matnni graphics2D ob'ektidagi to'rtburchaklar bilan cheklash uchun matnni ko'rsatishning o'rnatilgan usuli bormi?

Men Graphics2D.drawString dan foydalanishim mumkinligini bilaman, lekin u faqat matnning bir qatorini chizadi.

Men ham foydalanishim mumkinligini bilaman

FontMetrics fm= graphics.getFontMetrics(font);
Rectangle2D rect=fm.getStringBounds("Some Text",graphics);

Ba'zi Graphics2D graphics ob'ektida Font font yordamida ko'rsatilganda satr chegaralari haqida ma'lumot olish uchun.

Shunday qilib, men uni qandaydir to'rtburchak ichiga sig'dirish uchun ilmoqni boshlashim, ipimni sindirish va hokazolarni boshlashim mumkin edi.

Lekin men ularni yozmaslikni afzal ko'raman ...

Buni men uchun bajaradigan tayyor funksiya bormi?


person epeleg    schedule 26.08.2012    source manba
comment
Menga shaxsan Endryu tomonidan isbotlangan misol yoqadi, chunki bunga tez erishiladi. Biroq, men o'tmishda bu yondashuvdan foydalanganman java.sun .com/developer/onlineTraining/Media/2DText/   -  person MadProgrammer    schedule 26.08.2012
comment
Ikki muqobilning ijobiy va salbiy tomonlari bormi?   -  person epeleg    schedule 26.08.2012
comment
Endryuning yechimi osonroq, IMHO   -  person MadProgrammer    schedule 26.08.2012


Javoblar (4)


~10 satr kod bilan mukammal chiziq o'rash uchun vaqtinchalik JTextArea dan foydalaning:

static void drawWrappedText(Graphics g, String text, int x, int y, int w, int h) {
    JTextArea ta = new JTextArea(text);
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setBounds(0, 0, w, h);
    ta.setForeground(g.getColor());
    ta.setFont(g.getFont());
    Graphics g2 = g.create(x, y, w, h); // Use new graphics to leave original graphics state unchanged
    ta.paint(g2);
}
person Adam Gawne-Cain    schedule 04.02.2021
comment
Kimdir 8,5 yil oldin so'ragan savolimga javob berish haqida qayg'urayotganini ko'rish juda yoqimli. Men harakatni qadrlayman. Men nima uchun buni so'raganimni va nega o'tmishda hech qanday javobni qabul qilmaganimni bilmayman (men ochiq Q larni qoldirmaslikka harakat qilaman). Sizning javobingizni sinab ko'rish uchun menda ham muhit yo'q (buni qilishga vaqt ham yo'q) - ammo, uning qisqa, yaqinda va hech bo'lmaganda ko'p vaqt oldin so'raganimni bajarayotganini ko'rib, men sizning javobingizni qabul qilaman va jamoaga ovoz berishga ruxsat beraman. bu... - person epeleg; 07.03.2021

Bu siz qidirayotgan narsa bo'lishi mumkin:

StringUtils.java:

import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Globally available utility classes, mostly for string manipulation.
 * 
 * @author Jim Menard, <a href="/uzmailto:[email protected]">[email protected]</a>
 */
public class StringUtils {
  /**
   * Returns an array of strings, one for each line in the string after it has
   * been wrapped to fit lines of <var>maxWidth</var>. Lines end with any of
   * cr, lf, or cr lf. A line ending at the end of the string will not output a
   * further, empty string.
   * <p>
   * This code assumes <var>str</var> is not <code>null</code>.
   * 
   * @param str
   *          the string to split
   * @param fm
   *          needed for string width calculations
   * @param maxWidth
   *          the max line width, in points
   * @return a non-empty list of strings
   */
  public static List wrap(String str, FontMetrics fm, int maxWidth) {
    List lines = splitIntoLines(str);
    if (lines.size() == 0)
      return lines;

    ArrayList strings = new ArrayList();
    for (Iterator iter = lines.iterator(); iter.hasNext();)
      wrapLineInto((String) iter.next(), strings, fm, maxWidth);
    return strings;
  }

  /**
   * Given a line of text and font metrics information, wrap the line and add
   * the new line(s) to <var>list</var>.
   * 
   * @param line
   *          a line of text
   * @param list
   *          an output list of strings
   * @param fm
   *          font metrics
   * @param maxWidth
   *          maximum width of the line(s)
   */
  public static void wrapLineInto(String line, List list, FontMetrics fm, int maxWidth) {
    int len = line.length();
    int width;
    while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) {
      // Guess where to split the line. Look for the next space before
      // or after the guess.
      int guess = len * maxWidth / width;
      String before = line.substring(0, guess).trim();

      width = fm.stringWidth(before);
      int pos;
      if (width > maxWidth) // Too long
        pos = findBreakBefore(line, guess);
      else { // Too short or possibly just right
        pos = findBreakAfter(line, guess);
        if (pos != -1) { // Make sure this doesn't make us too long
          before = line.substring(0, pos).trim();
          if (fm.stringWidth(before) > maxWidth)
            pos = findBreakBefore(line, guess);
        }
      }
      if (pos == -1)
        pos = guess; // Split in the middle of the word

      list.add(line.substring(0, pos).trim());
      line = line.substring(pos).trim();
      len = line.length();
    }
    if (len > 0)
      list.add(line);
  }

  /**
   * Returns the index of the first whitespace character or '-' in <var>line</var>
   * that is at or before <var>start</var>. Returns -1 if no such character is
   * found.
   * 
   * @param line
   *          a string
   * @param start
   *          where to star looking
   */
  public static int findBreakBefore(String line, int start) {
    for (int i = start; i >= 0; --i) {
      char c = line.charAt(i);
      if (Character.isWhitespace(c) || c == '-')
        return i;
    }
    return -1;
  }

  /**
   * Returns the index of the first whitespace character or '-' in <var>line</var>
   * that is at or after <var>start</var>. Returns -1 if no such character is
   * found.
   * 
   * @param line
   *          a string
   * @param start
   *          where to star looking
   */
  public static int findBreakAfter(String line, int start) {
    int len = line.length();
    for (int i = start; i < len; ++i) {
      char c = line.charAt(i);
      if (Character.isWhitespace(c) || c == '-')
        return i;
    }
    return -1;
  }
  /**
   * Returns an array of strings, one for each line in the string. Lines end
   * with any of cr, lf, or cr lf. A line ending at the end of the string will
   * not output a further, empty string.
   * <p>
   * This code assumes <var>str</var> is not <code>null</code>.
   * 
   * @param str
   *          the string to split
   * @return a non-empty list of strings
   */
  public static List splitIntoLines(String str) {
    ArrayList strings = new ArrayList();

    int len = str.length();
    if (len == 0) {
      strings.add("");
      return strings;
    }

    int lineStart = 0;

    for (int i = 0; i < len; ++i) {
      char c = str.charAt(i);
      if (c == '\r') {
        int newlineLength = 1;
        if ((i + 1) < len && str.charAt(i + 1) == '\n')
          newlineLength = 2;
        strings.add(str.substring(lineStart, i));
        lineStart = i + newlineLength;
        if (newlineLength == 2) // skip \n next time through loop
          ++i;
      } else if (c == '\n') {
        strings.add(str.substring(lineStart, i));
        lineStart = i + 1;
      }
    }
    if (lineStart < len)
      strings.add(str.substring(lineStart));

    return strings;
  }

}

Siz buni o'z sinfiga qo'ygan bo'lardingiz, keyin sizda mavjud bo'lgan narsadan foydalaning:

FontMetrics fm= graphics.getFontMetrics(font);
Rectangle2D rect=fm.getStringBounds("Some Text",graphics);

wrap(String str, FontMetrics fm, int maxWidth) ga qo'ng'iroq qiling, bu sizning maxWidth ga mos ravishda o'ralgan List Stringsni qaytaradi, bu matn kiritiladigan Rectangle2D ning kengligi bo'ladi:

String text="Some Text";
FontMetrics fm= graphics.getFontMetrics(font);
Rectangle2D rect=fm.getStringBounds(text,graphics);
List<String> textList=StringUtils.wrap(text, fm, int maxWidth);

Ma'lumotnoma:

person David Kroukamp    schedule 26.08.2012

Men yordam beradigan kichik funktsiyani yozdim. 447 - kenglik mavjud bo'lib, siz matnni ko'rsatish uchun kerakli kenglikdan olishingiz mumkin.

private void drawTextUgly(String text, FontMetrics textMetrics, Graphics2D g2)
{
    // Ugly code to wrap text
    int lineHeight = textMetrics.getHeight();
    String textToDraw = text;
    String[] arr = textToDraw.split(" ");
    int nIndex = 0;
    int startX = 319;
    int startY = 113;
    while ( nIndex < arr.length )
    {
        String line = arr[nIndex++];
        while ( ( nIndex < arr.length ) && (textMetrics.stringWidth(line + " " + arr[nIndex]) < 447) )
        {
            line = line + " " + arr[nIndex];
            nIndex++;
        }
        GraphicsUtility.drawString(g2, line, startX, startY);
        startY = startY + lineHeight;
    }
}
person Nauman Khan    schedule 19.11.2012

ushbu javob dagi LabelRenderTest manbasiga qarang. U HTML/CSS-dan foydalanadi, tana kengligi CSS-dan foydalanib o'rnatiladi va shu bilan chiziqni o'rashni avtomatik qiladi.

person Andrew Thompson    schedule 26.08.2012
comment
Iltimos, agar muammoni hal qilishga yordam bergan bo'lsa, javobni qabul qiling. - person Andrew Thompson; 18.11.2020