当前位置:网站首页>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);
}

边栏推荐
- 2022-07-25 顾宇佳 学习笔记
- 想sink 到 redis-hash 里面 把 对象的属性和值都写进去 ,大佬们有Demo 吗?
- Functools module
- 网络入门——vlan及trunk概述
- Oracle 组合查询
- oracle清理含有引用分区的表的数据库磁盘空间
- Gossip: talk with your daughter about why you should learn culture lessons well
- 用shell来计算文本中的数字之和
- Usage of string class
- Word wrap: break word line feed is compatible with browsers
猜你喜欢

零号培训平台课程-2、SSRF基础

docker安装MySQL8.0.28

用户解锁SM04 SM12

Gossip: talk with your daughter about why you should learn culture lessons well

SQLite 常用功能整合

(2022 Hangdian multi school III) 1011.taxi (Manhattan maximum + 2 points)

杂谈:最近好多朋友谈出国……

(2022杭电多校三)1011.Taxi(曼哈顿最值+二分)

Using docker in MAC to build Oracle database server

js做一个红绿灯
随机推荐
(posted) comparison of Eureka, consumer and Nacos 2
【golang学习笔记2.0】 golang中的数组和切片
Which C4d cloud rendering platform to cooperate with?
yhb_sysbench
(2022 Hangdian multi school III) 1009.package delivery (greedy)
简单的轮播图
DRConv-pytorch改称输出和输入一样的尺寸
[wsl2] configure the USB camera connecting the USB device and using the host
Linear table -- stack and queue
QT连接sqlite数据库的错误及其修改办法
? Experiment 7 implementation of PHP management system based on MySQL
海康h9摄像头用xshell无法连接(没有启用ssh)
使用pip命令切换不同的镜像源
一款开源 OA 办公自动化系统
Overall dichotomy?
36 - new promise method: allsettled & any & race
The possibility of metauniverse from the perspective of technical principles: how Omniverse "built" Mars
Analysis of memory structure of C program code
SQLite 常用功能整合
请问有人使用oracle xstream 时出现个别capture延迟很大的吗,该如何解决延迟问题呢