본문 바로가기

JAVA/Swing

JAVA Swing 폰트에 outline 선 씌우기

사진 설명이 더 쉽다.

 

no-outline font

위와 같은 폰트에 outline을 씌워 아래와 같은 사진으로 만들어 그리고 싶을 때 말이다.

 

그러니까, 폰트에 테두리를 씌우고 싶을 때가 있을 것이다.

 

outline font

보통 다른 처리가 되어 있지 않은 트루타입 폰트 (TTF)를 자바에서 drawString을 통해 paint하게 되면 no-outline font로 나타나게 된다.

 

이 때 따로 그래픽 페인트를 만들어 outline을 씌울 수 있다.

 

public static void drawFancyString(Graphics2D g, String str, int x, int y, float size, Color internalColor) {
  if(str.length()==0)return;
  AffineTransform orig = g.getTransform();
  Font f = FontManager.getFont(size);
  TextLayout tl = new TextLayout(str, f, g.getFontRenderContext());
  AffineTransform transform = g.getTransform();
  FontMetrics fm = g.getFontMetrics(f);
  Shape outline = tl.getOutline(null);
  Rectangle bound = outline.getBounds();
  transform.translate(x, y+fm.getAscent());
  
  g.setTransform(transform);
  g.setColor(internalColor);
  g.fill(outline);
  g.setStroke(new BasicStroke(size/25));
  g.setColor(Color.BLACK);
  g.draw(outline);
  
  g.setTransform(orig);
}

내가 코드에서 실제로 사용한 함수인데, 가져가서 조금씩 변형하여 사용하면 된다.

 

문자열이 비어있을 때 굳이 리턴해준 이유는 TextLayout 초기화 부분에서 Exception이 발생하기 때문이다.

 

textlayout의 getOutline 함수를 통해 shape을 따오고, fill()를 통해 outline을 따로 그려준 것임.

 

setStroke()는 테두리의 두께를 설정하는 것.

 

마지막 줄은 최상위 계층 Graphics2D 패널의 Transform값을 원래대로 돌려놓는 코드다.