Java:用图像中间字符串替换文本并与自动换行对齐

时间:2018-09-01 16:40:42

标签: java string replace bufferedimage word-wrap

我对Java编程还是有点陌生​​,所以对文本的大量转储感到抱歉。非常感谢您抽出宝贵的时间阅读我当前的问题!

我正在开发软件,以帮助使用Java Swing加快棋盘游戏设计的过程。它需要一个用于游戏的纸牌CSV文件,您可以通过放置每列在纸牌上呈现的位置来构建虚拟纸牌,然后从这些位置自动生成CSV中的所有纸牌。

许多纸牌游戏都具有代表游戏中某些内容的符号,我希望能够将它们插入字符串的中间。我现在可以用符号替换整个字符串;因为它会检查string == a known rule是否在绘制符号。但是,我不知道如何在字符串中搜索一组特定的字符。如果找到它们,则从字符串中删除它们,然后在其位置绘制相应的符号。可以用魔术牌上的法术力符号看到一个很好的例子:https://cdn0.vox-cdn.com/uploads/chorus_asset/file/8039357/C0cIVZ5.png

因此字符串可以是:Gain 1 {GOLD} at the start of each tun. 并且它需要使用Rule类将{GOLD}替换为金色图片,其中包含要查找的字符串和一个替换后的缓冲图像。

我希望在不对符号大小使用硬限制的情况下进行此操作,但这不是硬性要求。最好的解决方案是缩放符号,使其高度与文本相同。

此方法获取缓冲的图像(无文字的卡片),并将文本覆盖在卡片顶部。

//Will modify the buffered image with the placeables
static public BufferedImage buildCard(BufferedImage start, int whichCardID) {
    //Copy so we don't lose our template
    BufferedImage ni = deepCopy(start); //ni = new image

    //The headers of the document
    String[] headers = MainWindow.loadedCards.get(0);

    //For each placeable, write down it's text
    for(int i=0; i<headers.length; i++) {
        //get current header
        String currentHeader = headers[i];

        //The Text
        String theText = MainWindow.loadedCards.get(whichCardID)[i];

        //The Settings
        PlaceableSettings theSettings = MainWindow.placeableSettings.get(currentHeader);

        //Make the change to the image
        //ni = writeToImage(ni, theText, theSettings);

        ///////New below
        boolean foundRule = false;

        //see if we have a rule to draw a graphic instead
        for(RuleMaster.Rule r : RuleMaster.rules) {
            if(r.keyword.equals(theText)) {
                //there is a rule for this!
                ni = drawRuleToImage(ni, r, theSettings);
                foundRule = true; //so we don't draw the current text
            }
        }
        //No rules for this

        //Make the change to the image if there are no rules
        if(foundRule == false)
            ni = writeToImage(ni, theText, theSettings);
    }
    return ni;
}

//Takes a buffered image and writes text into it at the location given
static public BufferedImage writeToImage(BufferedImage old, String text, PlaceableSettings setts) {
    //make new blank graphics
    BufferedImage bi = new BufferedImage(old.getWidth(), old.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    //write old image to it
    g2d.drawImage(old, 0, 0, null); //null was set to "this" when this was not static | Note ion case this breaks

    //write text on it
    g2d.setPaint(setts.getColor());
    g2d.setFont(setts.getFont());

    //Setup word wrap
    FontMetrics fm = g2d.getFontMetrics(setts.getFont());
    //    int rightSideBuffer = bi.getWidth() - 10;
    //Rectangle2D rect = fm.getStringBounds(text, setts.getX(), rightSideBuffer, g2d); // try just -'ing the x slot from the width below
    Rectangle2D rect = fm.getStringBounds(text, g2d); //this gets you the bounds for the entire image, need to remove space for x,y position


    //TODO: Problem: this is always length 1
    //Solution! No auto wrap, let the person define it as a setting
    @SuppressWarnings("unchecked")
    List<String> textList=StringUtils.wrap(text, fm, setts.getPixelsTillWrap() ); //width counted in # of characters

    //g2d.drawString(text, setts.getX(), setts.getY()); //old draw with no wrap



    for(int i=0; i< textList.size(); i++) {
        g2d.drawString(textList.get(i), setts.getX(), setts.getY() + ( i*(setts.getFont().getSize() + 2/*Buffer*/)));
    }

    //!!DEBUG
    if(EntryPoint.DEBUG) {
        Random r = new Random();
        g2d.setPaint(Color.RED);
        g2d.drawString(Integer.toString(textList.size()), 100, 50+r.nextInt(250));
        g2d.setPaint(Color.GREEN);
        g2d.drawString(Double.toString(rect.getWidth()), 200, 50+r.nextInt(250));
        g2d.setPaint(Color.PINK);
        //g2d.drawString(Integer.toString(( ((int) rect.getWidth()) - setts.getX())), 100, 250+r.nextInt(100));

    }

    //cleanup
    g2d.dispose();

    return bi;
}

//Takes a buffered image and draws an image on it at the location given
static public BufferedImage drawRuleToImage(BufferedImage old, RuleMaster.Rule rule, PlaceableSettings theSettings) {
    //make new blank graphics
    BufferedImage bi = new BufferedImage(old.getWidth(), old.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    //write old image to it
    g2d.drawImage(old, 0, 0, null); //null was set to "this" when this was not static | Note ion case this breaks

    g2d.drawImage(rule.image, theSettings.getX(), theSettings.getY(), null);

    //cleanup
    g2d.dispose();

    //System.exit(1);

    return bi;
}

每个规则仅包含要替换的字符串和要替换为的图像。

static public class Rule{
    //Text to look for
    String keyword;
    //image to replace it with
    BufferedImage image;

    public Rule (String key, BufferedImage img) {
        keyword = key;
        image = img;
    }
}

我正在尝试将此工具设计为可供许多人使用的工具,因此文本应该能够匹配用户添加的内容;尽管我目前的流程是使用诸如“ {M}”之类的字符串,但这可能是一个标准。

这方面的另一个大障碍是文本可以缠绕在卡片上,这意味着字符串和图像需要在提供的边界内缠绕在一起。

编辑1: 有一些想法,将尝试这种方法。在绘制字符串的“下一个”一半时,仍然看到边界可能存在问题;但我相信这可能有效。

//If found a rule mid text:

            //Split string in 2 at the rule match: strings 'start', and 'next'
            //Calculate x and y for symbol
            //x is the # of characters in ('start' % the word wrap width) +1 as the symbol is the next character, then multiply that by the character size of the font
            //y is the integer of dividing the # of characters in 'start' by word wrap width multiplied by the font height
            //Draw Start of String
            //Draw symbol

            //next x = sym.x + sym width //TODO next (x,y) math

1 个答案:

答案 0 :(得分:0)

我能够根据文本大小提前弯曲来解决此问题。通过使用已知大小的图像,可以提前知道正确的包装方式。

然后我遍历每一行。我看过在要替换的文本字符串中是否有拆分。我他们照常绘制了字符串的第一部分。使用int pixelWidth = ni.getGraphics().getFontMetrics().stringWidth(splitString[j]);计算字符串的宽度。然后以相同的Y绘制图像,但是将前一个字符串的宽度添加到X。然后将图像的当前宽度添加到X并继续循环;根据需要绘制图像和字符串。