簡體   English   中英

為什么屏幕外圖像渲染不起作用?

[英]Why does my offscreen image rendering doesn't work?

我必須用Java創建一個小工具。 我的任務是將文本(單個字母)呈現到屏幕上的圖像,並計算指定矩形內的所有白色和黑色像素。

/***************************************************************************
 * Calculate black to white ratio for a given font and letters
 **************************************************************************/
private static double calculateFactor(final Font font,
        final Map<Character, Double> charWeights) {

    final char[] chars = new char[1];
    double factor = 0.0;

    for (final Map.Entry<Character, Double> entry : charWeights.entrySet()) {
        final BufferedImage image = new BufferedImage(height, width,
                BufferedImage.TYPE_INT_ARGB);
        chars[0] = entry.getKey();
        final Graphics graphics = image.getGraphics();
        graphics.setFont(font);
        graphics.setColor(Color.black);
        graphics.drawChars(chars, 0, 1, 0, 0);

        final double ratio = calculateBlackRatio(image.getRaster());
        factor += (ratio * entry.getValue());

    }
    return factor / charWeights.size();
}
/***************************************************************************
 * Count ration raster
 **************************************************************************/
private static double calculateBlackRatio(final Raster raster) {

    final int maxX = raster.getMinX() + raster.getWidth();
    final int maxY = raster.getMinY() + raster.getHeight();
    int blackCounter = 0;
    int whiteCounter = 0;

    for (int indexY = raster.getMinY(); indexY < maxY; ++indexY) {
        for (int indexX = raster.getMinX(); indexX < maxX; ++indexX) {

            final int color = raster.getSample(indexX, indexY, 0);
            if (color == 0) {
                ++blackCounter;
            } else {
                ++whiteCounter;
            }
        }
    }
    return blackCounter / (double) whiteCounter;
}

問題是raster.getSample總是返回0。

我做錯了什么 ?

也許字符根本不吸引人。 如果我沒記錯的話,.drawChars()方法將繪制到Y基線。 因此,我認為您必須將字體高度添加到Y值。

如果我沒記錯的話,可以在x = 0,y = 0處繪制字符,其中x,y是“ 此圖形上下文的坐標系中第一個字符的基線 ”因為基線在...的底部字符,則將它們繪制在圖像上方 使用x = 0,y =高度。
另外,正確的構造函數是: BufferedImage(int width, int height, int imageType) :反轉寬度和高度。

OK,PhiLho的nas Waverick的答案是正確的。 另外,我必須清除背景並將字體顏色更改為黑色:)

final Graphics graphics = image.getGraphics();
            graphics.setFont(font);
            graphics.setColor(Color.white);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.black);
            graphics.drawChars(chars, 0, 1, 0, height);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM