当前位置:网站首页>drawImage方法第一次调用不显示图片的解决方式
drawImage方法第一次调用不显示图片的解决方式
2022-07-27 06:32:00 【爱学习的大雄】
问题
在写坦克大战的时候,子弹击中敌方坦克后会显示爆炸效果,但是子弹第一次击中敌方坦克时不会显示爆炸效果。通过debug后发现是Graphics类调用drawImage绘制图片时出现问题。
boolean b=false;
b=g.drawImage(imgError,thex(i),they(j),this);
原因
在开始的一段时间内g.drawImage返回值b经常会是false,导致显示不正常,但是,只要显示一段时间后,即该函数被调用若干次后返回值b就会一直是true,再也不会返回false了。
当drawImage这个方法中的图片没有被完全加载的时候,这个方法会返回false。drawImage方法是在调用的时候才加载所需要的图片,所以第一次调用的时候,图片没有被完全加载,造成显示的不正常,甚至不显示图片,此后,图片由于方法调用被加载,以后再以这幅图片为参数的时候,就可以正常显示了。
解决方式
使用MediaTracker类:
Image img = Toolkit.getDefaultToolkit().getImage(imgPath);
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0); //img就是你要显示的图片
t.waitForAll();
将这段代码在drawImage()之前调用,MediaTracker可以确保你的图片在DRAW前被加载以备使用。通过addImage方法加入一个Image并符上一个ID号,waitForAll()等待加入的所有图片被加载完毕。也就是说先前只要正常显示过一次了,那么应该图片已经加载好了,此后此图片就再也不会出现返回false而不能正常显示了。
如果只使用drawImage那么是在调用的时候加载图片,如果这个图片在本地,那么加载好图片的速度相当的快。再次调用drawImage方法的时候就能正常显示了。也可以在初始化时对每个图片显示一下,直到每个图片显示都返回true,这样之后就不会再出现不正常的显示了。
示例
//解决第一次不显示图片的问题
MediaTracker t = new MediaTracker(this);
t.addImage(images[16-bomb.getLife()], 0);
try {
t.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
g.drawImage(images[16-bomb.getLife()],bomb.getX(),bomb.getY(),60,60,this);
//让这个炸弹是生命值减少
bomb.lifeDown();
//如果bomb的life为0,则从集合中去除
if (bomb.getLife()==0){
bombs.remove(bomb);
}

边栏推荐
猜你喜欢

使用pip命令切换不同的镜像源

Use the PIP command to switch between different mirror sources
![[wsl2] configure the USB camera connecting the USB device and using the host](/img/03/7ebc7eebeda1598c8f4fdd1e9188c7.png)
[wsl2] configure the USB camera connecting the USB device and using the host

Jmeter:接口自动化测试-BeanShell对数据库数据和返回数据比较

2022 0726 Gu Yujia's study notes

在Perl程序中暴露Prometheus指标

Generics -- learn it, and there are many benefits

Essay: college entrance examination

A small cotton padded jacket with air leakage

Using loops to process data in tables in kettle
随机推荐
单臂路由(讲解+实验)
12. Integer to Roman整数转罗马数字
闭散列和开散列解决哈希冲突
Will Flink CDC constantly occupy Oracle's memory by extracting Oracle's data, and finally cause oracle-040
35. Search Insert Position 搜索插入位置
漏风的小棉袄……
12. Integer to Roman
网络入门——vlan及trunk概述
在rhel7.3中编译和使用log4cxx
ShowDoc漏洞学习——CNVD-2020-26585(任意文件上传)
Algorithm -- Fibonacci sequence (kotlin)
The difference between critical section (the code that accesses critical resources in each thread) and mutex (mutex between processes, shared memory, virtual address)
centos7中关闭oracle服务自动启动的功能
Flutter实战-请求封装(一)
【golang学习笔记2.0】 golang中的数组和切片
MySQL2
一个优先级顺序的SQL问题
高级IO提纲
简单的轮播图
[wsl2] configure the USB camera connecting the USB device and using the host