java图片循环_java – 如何实现无限图像循环?

您可以通过多种方式实现此目标,但基本前提是,您需要某种滚动偏移来确定基本图像的开始.

然后,您需要在它之前和之后填充区域(如果图像小于可用高度),直到空间被填满.

以下示例使用javax.swing.Timer以给定量更新偏移量.然后,paintComponent方法渲染其前后的所有空间,包括当前图像位置.

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class ScrollingBackground {

public static void main(String[] args) {

new ScrollingBackground();

}

public ScrollingBackground() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {

}

JFrame frame = new JFrame("Testing");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

frame.add(new BackgroundPane());

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

});

}

public class BackgroundPane extends JPanel {

private BufferedImage bg;

private int yOffset = 0;

private int yDelta = 4;

public BackgroundPane() {

try {

bg = ImageIO.read(new File("Background.png"));

} catch (IOException ex) {

ex.printStackTrace();

}

Timer timer = new Timer(40, new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

yOffset += yDelta;

if (yOffset > getHeight()) {

yOffset = 0;

}

repaint();;

}

});

timer.start();

}

@Override

public Dimension getPreferredSize() {

return bg == null ? new Dimension(200, 200) : new Dimension(bg.getWidth(), bg.getHeight());

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

if (bg != null) {

Graphics2D g2d = (Graphics2D) g.create();

int xPos = (getWidth() - bg.getWidth()) / 2;

int yPos = yOffset;

while (yPos > 0) {

yPos -= bg.getHeight();

g2d.drawImage(bg, xPos, yPos, this);

}

yPos = yOffset;

while (yPos < getHeight()) {

g2d.drawImage(bg, xPos, yPos, this);

yPos += bg.getHeight();

}

g2d.dispose();

}

}

}

}

你可以通过使用后备缓冲区和/或subImage来乐观这一点,但是你明白了……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值