概要

Windowの形を図形で切り抜きした場合に生じる縁のジャギーをソフトクリッピング効果でなめらかに変更します。

サンプルコード

int width = image.getWidth();
int height = image.getHeight();
Shape shape = new RoundRectangle2D.Float(0f, 0f, width / 2f, height / 2f, 50f, 50f);

BufferedImage clippedImage = makeClippedImage(image, shape);

JWindow window = new JWindow();
window.setBackground(new Color(0x0, true));
window.getContentPane().add(makePanel(clippedImage));
window.pack();
window.setLocationRelativeTo(((AbstractButton) e.getSource()).getRootPane());
window.setVisible(true);
// ...
private static BufferedImage makeClippedImage(BufferedImage source, Shape shape) {
  int width = source.getWidth();
  int height = source.getHeight();

  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2 = image.createGraphics();
  // g2.setComposite(AlphaComposite.Clear);
  // g2.fillRect(0, 0, width, height);

  g2.setComposite(AlphaComposite.Src);
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  // g2.setColor(Color.WHITE);
  g2.fill(shape);

  g2.setComposite(AlphaComposite.SrcAtop);
  g2.drawImage(source, 0, 0, null);
  g2.dispose();

  return image;
}
View in GitHub: Java, Kotlin

解説


  • Corretto 1.8.0_212(Windows 10環境)でソフトクリッピング効果を使用すると描画がおかしくなる?
    openjdk version "1.8.0_212"
    OpenJDK Runtime Environment Corretto-8.212.04.2 (build 1.8.0_212-b04)
    OpenJDK 64-Bit Server VM Corretto-8.212.04.2 (build 25.212-b04, mixed mode)

  • Corretto 11.0.3では正常
    openjdk version "11.0.3" 2019-04-16 LTS
    OpenJDK Runtime Environment Corretto-11.0.3.7.1 (build 11.0.3+7-LTS)
    OpenJDK 64-Bit Server VM Corretto-11.0.3.7.1 (build 11.0.3+7-LTS, mixed mode)
  • AdoptOpenJDK 1.8.0_212では正常
    openjdk version "1.8.0_212"
    OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_212-b03)
    OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.212-b03, mixed mode)
  • Corretto 1.8.0_222で修正されたことを確認
    openjdk version "1.8.0_222"
    OpenJDK Runtime Environment Corretto-8.222.10.3 (build 1.8.0_222-b10)
    OpenJDK 64-Bit Server VM Corretto-8.222.10.3 (build 25.222-b10, mixed mode)

参考リンク

コメント