2010-01-27 5 views
0

자바로 작은 도구를 만들어야합니다. 화면상의 이미지에 텍스트 (단일 문자)를 렌더링하고 지정된 사각형 내 모든 흰색 및 검은 색 픽셀을 계산하는 작업이 있습니다.왜 오프 스크린 이미지 렌더링이 작동하지 않습니까?

/*************************************************************************** 
* 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는 x, y는 0 = "첫 번째 문자의 베이스 라인을 [...]이 그래픽스 문맥의 좌표계." 이후 기준선이 문자의 맨 아래에있는 경우 위의 이미지를 위에 그립니다. x = 0, y = height를 사용하십시오.
올바른 생성자는 다음과 같습니다. BufferedImage(int width, int height, int imageType) : 너비와 높이가 뒤집 혔습니다.

2

아마도 문자는 이미지에 전혀 그려지지 않을 것입니다. .drawChars() 메서드가 올바르게 호출 된 경우 Y 기준선을 그립니다. 그래서 당신은 Y 값에 글꼴 높이를 추가해야한다고 생각합니다. 내가 잘못 아니에요 경우

1

확인 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); 
관련 문제