TITLE:TexturePaintを使って背景に画像を表示

TexturePaintを使って背景に画像を表示

編集者:Terai Atsuhiro~

作成日:2004-09-20
更新日:2023-10-12 (木) 10:58:52
  • category: swing folder: TexturePaint title: TexturePaintを使って背景に画像を表示 tags: [TexturePaint, BufferedImage, Graphics2D] author: aterai pubdate: 2004-09-20T16:06:29+09:00 description: TexturePaintを使用して背景にタイル状に画像を貼り付けます。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTVUeXC5lI/AAAAAAAAAnc/CWUYfOODy1E/s800/TexturePaint.png

概要

TexturePaintを使用して背景にタイル状に画像を貼り付けます。

概要

TexturePaintを使用して背景にタイル状に画像を貼り付けます。

#screenshot

サンプルコード

#spanend
 URL url = getClass().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);
#spandel

#spanend
 public void paintComponent(Graphics g) {
   Graphics2D g2 = (Graphics2D)g;
   g2.setPaint(texture);
   g2.fillRect(0, 0, getWidth(), getHeight());
   super.paintComponent(g);
 }
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#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
  • &jnlp;
  • &jar;
  • &zip;

解説

このサンプルでは、BufferedImageからTexturePaintを生成し、これをGraphics2D#setPaintメソッドで設定してパネル全体を塗りつぶしています。

解説

  • BufferedImageを生成
  • このImageGraphics#drawImage(...)で描画するのではなく、TexturePaintを作成しGraphics2D#setPaintメソッドで設定してパネル全体の塗りつぶしを実行

参考リンク

参考リンク

コメント

コメント