Swing/TexturePaint のバックアップの現在との差分(No.4)
#navi(contents-page-name): No such page: ST
2023-10-12 (木) 10:58:52
概要
TexturePaint
を使用して背景にタイル状に画像を貼り付けます。
Screenshot
Advertisement
サンプルコード
#spanend
#spanadd
String path = "example/16x16.png";
#spanend
#spanadd
ClassLoader cl = Thread.currentThread().getContextClassLoader();
#spanend
#spanadd
BufferedImage bi = Optional.ofNullable(cl.getResource(path)).map(url -> {
#spanend
try (InputStream s = url.openStream()) {
return ImageIO.read(s);
} catch (IOException ex) {
ex.printStackTrace();
return makeMissingImage();
}
#spanadd
}).orElseGet(MainPanel::makeMissingImage);
#spanend
#spanadd
texture = new TexturePaint(bi, new Rectangle(bi.getWidth(), bi.getHeight()));
#spanend
#spanadd
panel = new JPanel() {
#spanend
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(texture);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, KotlinURL url = MainPanel.class.getResource("16x16.png"); BufferedImage img = null; try { img = ImageIO.read(url); }catch(IOException ioe) { ioe.printStackTrace(); } Rectangle2D r2d = new Rectangle2D.Double(0,0,img.getWidth(),img.getHeight()); texture = new TexturePaint(img, r2d);
解説
-
BufferedImage
を生成 - この
Image
をGraphics#drawImage(...)
で描画するのではなく、TexturePaint
を作成しGraphics2D#setPaint
メソッドで設定してパネル全体の塗りつぶしを実行
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setPaint(texture); g2.fillRect(0, 0, getWidth(), getHeight()); super.paintComponent(g); }
参考リンク
- ST/BackgroundImage?