TexturePaintを使って背景に画像を表示
Total: 13996
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
TexturePaint
を使用して背景にタイル状に画像を貼り付けます。
Screenshot
Advertisement
サンプルコード
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);
}
}
View in GitHub: Java, Kotlin解説
BufferedImage
を生成- この
Image
をGraphics#drawImage(...)
で描画するのではなく、TexturePaint
を作成しGraphics2D#setPaint
メソッドで設定してパネル全体の塗りつぶしを実行