我正在尝试创建一个简单的程序,它显示一个位图僵尸图片,然后使用AffineTransform和Thread旋转它。我遵循了我必须完成的例子,但是每当我运行程序时,僵尸位图只旋转一次并停止。另外,由于某种原因,当我绘制僵尸位图时,图像在y轴上部分脱离屏幕。
所以我的问题是:为什么位图不旋转,为什么位图离开屏幕。
守则如下:
import java.awt.*;// Graphics class
import java.awt.geom.*;
import java.net.*;//URL navigation
import javax.swing.*;//JFrame
import java.util.*;//Toolkit
public class BitMapZombies2 extends JFrame implements Runnable
{
private Image zombieOneRight;
Thread zombieRun;
public static void main (String[] args)
{
new BitMapZombies2();
}
public BitMapZombies2()
{
super("Bit Map Zombies..RUN FOR YOUR LIFE!!!");
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit Zkit = Toolkit.getDefaultToolkit();
zombieOneLeft = Zkit.getImage(getURL("_images/_production_images/zombie_1_left_75h.png"));
zombieOneRight = Zkit.getImage(getURL("_images/_production_images/zombie_1_right_75h.png"));
zombieRun = new Thread(this);
zombieRun.start();
}
AffineTransform zombieIdentity = new AffineTransform();
private URL getURL(String filename)
{
URL url = null;
try
{
url = this.getClass().getResource(filename);
}
catch (Exception e) {}
return url;
}
public void paint(Graphics z)
{
Graphics2D z2d = (Graphics2D) z;
AffineTransform ZombiePowered = new AffineTransform();
z2d.setColor(Color.BLACK);
z2d.fillRect(0,0, 800, 600);
ZombiePowered.setTransform(zombieIdentity);
ZombiePowered.rotate(2,37.5,37.5);
z2d.drawImage(zombieOneRight,ZombiePowered,this);
}
public void run()
{
Thread zT = Thread.currentThread();
while (zT == zombieRun)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
}
}很感谢你能帮我的忙。
发布于 2014-02-17 08:43:22
注释您的代码:
AffineTransform ZombiePowered = new AffineTransform();//Create an Id. transform
ZombiePowered.setTransform(zombieIdentity);//Set it as a copy of an Id. transform
ZombiePowered.rotate(2, 37.5, 37.5);//Concatenate the rotation with the Id. transform
z2d.drawImage(zombieOneRight, ZombiePowered, this);//Apply the rotation因此,你总是旋转的2 your你的形象。如果您在“画图”方法的末尾执行此赋值:
zombieIdentity = ZombiePowered; 下一次,当您绘制图像时,它将旋转2 2rads更多。关于这个位置的问题,看看旋转javadoc:
将此转换与围绕锚点旋转坐标的转换相连接。该操作等效于将坐标转换为使锚点位于原点(S1),然后将其围绕新原点(S2)旋转,最后将中间原点恢复到原始锚点(S3)的坐标。 此操作等效于以下调用序列: 转换(锚,锚);// S3:最终平移旋转(θ);// S2:围绕锚转换旋转(-anchorx,-anchory);// S1:将锚转换为原点
希望能帮上忙。
发布于 2014-02-17 07:20:22
一旦创建了转换,就需要将其应用到图形上下文中.
public void paint(Graphics z)
{
//...
z2d.setTransform(ZombiePowered);
//...
}一旦应用了转换,它将影响在转换之后绘制到Graphics上下文的所有内容,因此您需要重置它或引用它。有很多方法可以做到这一点,但是最简单的方法是创建一个Graphics上下文的副本,当您不再需要它时,只创建它的dispose .
public void paint(Graphics z)
{
Graphics2D z2d = (Graphics2D) z.create();
//...
z2d.dispose();
}而且,这只是我,但我会创建一个新的实例的AffineTransform,这些事情很容易完全搞砸.
https://stackoverflow.com/questions/21822641
复制相似问题