【Swing】如何重复绘制frame背景图片

teemai 2012-02-01 07:20:59
相信大家都知道在web开发中,css有一个样式就是repeat背景图片的:background-repeat 属性设置是否及如何重复背景图像。

默认地,背景图像在水平和垂直方向上重复。


body
{
background-image: url(stars.gif);
background-repeat: repeat-x;
}


我现在想在JFrame上做类似的操作,如何实现?

首先JFrame里面是没办法绘图的,只能在JFrame的ContentPane里面绘图,我自定义一个JPanel,覆盖paintComponent方法,在里面绘制背景,再把它设置为JFrame的ContentPane,关键是我看了Graphics的API,没有直接x轴或y轴重复绘制的方法。难道要我去计算frame的宽度,然后循环去drawImage(Image img, int x, int y, ImageObserver observer) ??


...全文
103 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunyiz 2012-02-03
  • 打赏
  • 举报
回复
想延伸的重复画就用 TexturePaint
TexturePaint 要用 BufferedImage 来填充

Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(new TexturePaint(buffImage, new Rectangle2D.Float(
0, 0, buffImage.getWidth(), buffImage.getHeight())));
g2d.fillRect(0, 0, this.getWidth(), buffImage.getHeight());
sunyiz 2012-02-03
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 huxiweng 的回复:]
那是拉伸还是延伸?
我的需求是沿着x轴repeat啊。
[/Quote]
拉伸,不过你这个图是单像素重复
拉伸和延伸是一样的效果,所以用这个就可以实现了
teemai 2012-02-03
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 sunyiz 的回复:]

汗 让它自动延生去画就行了啊
g.drawImage(imgBg, x, y, getWidth(), getHeight(), null);
就行啊,不用循环画
[/Quote]

那是拉伸还是延伸?
我的需求是沿着x轴repeat啊。
sunyiz 2012-02-02
  • 打赏
  • 举报
回复
汗 让它自动延生去画就行了啊
g.drawImage(imgBg, x, y, getWidth(), getHeight(), null);
就行啊,不用循环画
zhe_bu_shi_majia 2012-02-01
  • 打赏
  • 举报
回复
JDK没有提供直接的绘图API吧,需要用第三方jar包
teemai 2012-02-01
  • 打赏
  • 举报
回复
有没有其他的方法!?
teemai 2012-02-01
  • 打赏
  • 举报
回复
原始图片:


效果:
teemai 2012-02-01
  • 打赏
  • 举报
回复
我的代码:


JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {

Image imgBg = new ImageIcon("./Resource/bg.gif").getImage();
for (int i = 0, x = 0, y = 0; i <= Mainframe.WIDTH / imgBg.getWidth(null) + 1; i++) {
g.drawImage(imgBg, x, y, imgBg.getWidth(null), getHeight(), null);
x += imgBg.getWidth(null);
}

}
};

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧