• 追加された行はこの色です。
  • 削除された行はこの色です。
#navi(../)
*TexturePaintを使って背景に画像を表示 [#vf616c16]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-09-20~
更新日:&lastmod;
---
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
---
* 概要 [#summary]
`TexturePaint`を使用して背景にタイル状に画像を貼り付けます。

#contents
**概要 [#ff4c7c60]
TexturePaintを使用して背景にタイル状に画像を貼り付けます。
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTVUeXC5lI/AAAAAAAAAnc/CWUYfOODy1E/s800/TexturePaint.png)

http://terai.xrea.jp/swing/texturepaint/screenshot.png
* サンプルコード [#sourcecode]
#code(link){{
String path = "example/16x16.png";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
BufferedImage bi = Optional.ofNullable(cl.getResource(path)).map(url -> {
  try (InputStream s = url.openStream()) {
    return ImageIO.read(s);
  } catch (IOException ex) {
    ex.printStackTrace();
    return makeMissingImage();
  }
}).orElseGet(MainPanel::makeMissingImage);
texture = new TexturePaint(bi, new Rectangle(bi.getWidth(), bi.getHeight()));
panel = new JPanel() {
  @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);
  }
}
}}

**サンプルコード [#u3a94734]
 URL 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);
* 解説 [#explanation]
- `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);
 }
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/java/awt/TexturePaint.html TexturePaint (Java Platform SE 8)]
- [[JPanelの背景に画像を並べる>Swing/BackgroundImage]]

-[[サンプルを起動>http://terai.xrea.jp/swing/texturepaint/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/texturepaint/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/texturepaint/src.zip]]
**解説 [#j85ba7cb]
このサンプルでは、BufferedImageからTexturePaintを生成し、これをGraphics2D#setPaintメソッドで設定してパネル全体を塗りつぶしています。
**参考リンク [#nc4c81eb]
-[[JPanelの背景に画像を並べる>Swing/BackgroundImage]]

**コメント [#e3931dfe]
* コメント [#comment]
#comment
#comment