GAMES LESSON TEN: Image Transforms

In this activity we will used the following three images:

We will use an instance of the AffineTransform class to flip the images so that they face in the opposite direction. In fact, here is the critical code in which the flip is accomplished:

Graphics2D dd = (Graphics2D)g; AffineTransform atf = new AffineTransform(); for(int i=0; i<pigs.length; i++){ Image ci = pigs[i]; g.drawImage(ci,10+130*i,10,this); atf.setToTranslation(10+130*i,120); atf.scale(-1,1); atf.translate(-ci.getWidth(this),0); dd.drawImage(ci,atf,null); } } }

You should notice that we first must make an instance of the Graphics2D class before we can do anything of any use with the AffineTransform class. The AffineTransform method only works with the Graphics2D version of the drawImage method.

import java.awt.*; import java.applet.*; import java.awt.geom.AffineTransform; public class PIG extends Applet{ Dimension d; Image pigs[]=new Image[3]; public void init(){ d = getSize(); for(int i = 0; i<pigs.length; i++){ pigs[i] = getImage(getDocumentBase(), "images/pig" + (i+1) + ".gif"); } } public void paint(Graphics g){ g.setColor(Color.yellow); g.fillRect(0,0,d.width,d.height); Graphics2D dd = (Graphics2D)g; AffineTransform atf = new AffineTransform(); for(int i=0; i<pigs.length; i++){ Image ci = pigs[i]; g.drawImage(ci,10+130*i,10,this); atf.setToTranslation(10+130*i,120); atf.scale(-1,1); atf.translate(-ci.getWidth(this),0); dd.drawImage(ci,atf,null); } } }


ASSIGNMENT: