2010-01-27 85 views
0

我必須在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; 
} 

的probllem是raster.getSample總是返回0

我做了什麼錯?

回答

2

如果我沒有記錯的話,你在x = 0戰平字符,Y = 0,其中x,y是「第一個字符的基線[...]在此圖形上下文的座標系。」 由於基線位於字符的底部,您可以在之上繪製的圖像。 使用x = 0,y =高度。
另外,正確的構造函數是:BufferedImage(int width, int height, int imageType):你倒過來的寬度和高度。

2

也許字符根本不是繪製到圖像上。如果我記得正確的.drawChars()方法繪製到Y-基線。所以你我認爲你必須將字體高度添加到Y值。

1

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);