我必須在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
我做了什麼錯?