2010-01-27 88 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);