Workshop for Programming And Systems Management Teachers Chapter 8 Drawing and Animation

advertisement
Workshop for Programming And
Systems Management Teachers
Chapter 8
Drawing and Animation
Georgia Institute of Technology
Learning Goals
• Understand at a conceptual and practical level
–
–
–
–
–
–
–
How to get a graphics object to use for drawing
How to set the color
How to set the font
How to draw strings
How to draw simple outlined shapes
How to draw filled shapes
How to use Java2D classes for more complex
drawing
– How to do animation
Georgia Institute of Technology
Drawing on a Picture
• What if we want to draw something on a picture?
• How about drawing a grid of lines on top of the
picture
– We could just set the pixels to black to make up the
lines
• We could add vertical lines every 5 pixels
– Start x = 0, x < width, x += 5
– Start y= 0, y < height, y++
• We could add horizontal lines every 5 pixels
– Start y = 0, y < height, y+=5
– Start x=0, x < width, x++
Georgia Institute of Technology
Drawing Lines Exercise
• Write a method to draw
horizontal and vertical
lines on the current
picture
– Lines every 5 pixels in x
and y
• You will probably want to
break this into two
methods
– drawHorizontalLines
– drawVerticalLines
Georgia Institute of Technology
Drawing Other Shapes
• How would you draw a circle on a picture?
• How would you draw a string of characters?
• You still would need to set the pixel colors of
certain pixels
– Which pixels?
• Java has a way of doing these things
– Using a Graphics object
– You can draw on a picture object
• By getting the graphics object from it
– picture.getGraphics();
Georgia Institute of Technology
AWT Graphics Class
• Methods of the Graphics
class in the java.awt
package let you paint
– Pick a color to use
– Draw some shapes
• Circles, Rectangles, Lines,
Polygons, Arcs
– Shapes drawn on top of
other shapes will cover
them
– Set the font to use
• Draw some letters
(strings)
Georgia Institute of Technology
Working with Color
• To create a new color
– Use new Color(red,green,blue)
• There are predefined colors
– red, green, blue, black, yellow, gray, magenta, cyan,
pink, orange
– To use these do: Color.red or Color.RED
• Set the current drawing color using
– graphics.setColor(highlightColor);
• Get the current drawing color using
– Color currColor = graphics.getColor();
Georgia Institute of Technology
Graphics Environment
• Graphics are often positioned by their top left corner
• Coordinate units are measured in pixels
0,0
+X
0, 0 is at the top left
X increases to the right
Y increases going down the page
+Y
400,200
Georgia Institute of Technology
Drawing Circles and Ellipses
• graphics.drawOval(x,y,width,
height)
• graphics.fillOval(x,y,width,
height)
• Give the x and y of the upper
left corner of the enclosing
rectangle
x,y
height
– Not a point on the circle or
ellipse
• Give the width and height of
the enclosing rectangle
– To make a circle use the same
value for the width and height
Georgia Institute of Technology
width
Draw Circle Exercise
• In DrJava create a picture
from beach.jpg
– Add a yellow circle to
represent the sun in the
sky of the beach.jpg picture
– Save the new image with
picture.write(fileName);
Georgia Institute of Technology
Working with Fonts
• Create a font with the font name, style, and point
size
– Font labelFont = new Font(“TimesRoman”,
Font.BOLD, 24);
– Font normalFont = new Font(“Helvetica”,Font.PLAIN,
12);
• Set the current font
– g.setFont(labelFont);
• Get font information
– g.getStyle(), g.getSize(), g.getName(), g.getFamily
Georgia Institute of Technology
Working with Strings
• To draw a string
– g.drawString(“test”,leftX,baselineY);
• Use FontMetrics class for drawing information
– FontMetrics currFontMetrics = g.getFontMetrics();
– int baselineY = currFontMetrics.getHeight() currFontMetrics.getDescent();
– int width = currFontMetrics.stringWidth(“test”);
leftX
ascent
test string
baselineY
leading
height
descent
Georgia Institute of Technology
Add a String to a Picture Exercise
• Add your name to a
picture
– Set the color to draw with
– Set the font to use when
drawing the string
– Draw a string near the
bottom left of the picture
– If you have time center the
string
Georgia Institute of Technology
Drawing Lines and Polygons
• Line
x1,y1
– g.drawLine(x1,y1,x2,y2);
• Polygon
– Outlined Polygon
• g.drawPolygon(xArray,yArray,numPoints);
• g.drawPolygon(currPolygon);
– Filled Polygon
• g.fillPolygon(xArray, yArray, numPoints);
• g.fillPolygon(currPolygon);
Georgia Institute of Technology
x2,y2
Drawing Lines Exercise
• Write a method for adding
two crossed lines to a
picture
– Using a passed color
• Start one line at the top
left corner of the picture
– End it at the bottom right
corner of the picture
• Start the other line at the
bottom left of the picture
– End it at the top right
Georgia Institute of Technology
Drawing Arcs
• Arcs
– Outlined Arc
• g.drawArc(topLeftX, topLeftY, width, height, startAngle,
arcAngle);
– Filled Arc
• g.fillArc((topLeftX, topLeftY, width, height, startAngle,
arcAngle);
Georgia Institute of Technology
Drawing Rectangles
• Rectangle
– Outlined Rectangle
• g.drawRect(topLeftX, topLeftY, width, height);
– Filled Rectangle
• g.fillRect(topLeftX,topLeftY,width,height);
– Outlined Rounded Rectangle
• g.drawRoundRect(topLeftX,topLeftY,width,height,arcWidth,ar
cHeight);
– Filled Rounded Rectangle
• g.fillRoundRect(topLeftX,topLeftY,width,height,arcWidth,arcH
eight);
Georgia Institute of Technology
Drawing on a Blank Picture
• You can make pictures from the “blank” files
– They will have all white pixels
– 640x480.jpg
– 7inX95in.jpg
• You can also create a “blank” picture with a
width and height
– They will have all black pixels
– Picture blankPicture = new Picture(width,height);
Georgia Institute of Technology
Draw a Picture Exercise
• Create a method that will
draw a simple picture
–
–
–
–
–
Use at least one rectangle
Use at least one polygon
Use at least one oval
Use at least one line
Use at least one arc
Georgia Institute of Technology
Precision Drawings
• How would you draw a
stack of filled rectangles
starting from the lightest
one at the bottom right
and the darkest one at
the top left.
– With 10 pixels between
each
– Not easy with drawing
packages
Georgia Institute of Technology
Draw Filled Rectangles Method
/**
* Method to draw a picture with a succession of filled rectangles
* with the top left corner the darkest and the bottom right the
* lightest
* @return the picture with the filled rectangles
*/
public static Picture drawFilledRectangles()
{
Picture p = new Picture(250,250);
Graphics g = p.getGraphics();
Color color = null;
// loop 25 times
for (int i = 25; i > 0; i--)
{
color = new Color(i * 10, i * 5, i);
g.setColor(color);
g.fillRect(0,0,i*10,i*10);
}
// show the picture
p.show();
// return the picture
return p;
}
Georgia Institute of Technology
Java 2D Graphics
• Newer drawing classes
– More object-oriented
– Instead of drawOval() or fillOval() you create a Ellipse2D object
and ask a 2d graphics object to draw or fill it
– Geometric shapes are in the java.awt.geom package
• Advanced Drawing
– Support for different types of brushes
• Line thickness, dashed lines, etc
–
–
–
–
Supports cubic curves and general paths
Drawing of gradients and textures
Move, rotate, scale and shear text and graphics
Create composite images
Georgia Institute of Technology
Java 2D Demo
• Open a console window
• Change directory to
C:\jdk\demo\jfc\Java2D
• Run the demo
java –jar Java2Demo.jar
• The source code is
inC:\jdk\demo\jfc\Java2D\
src
Georgia Institute of Technology
How To Use Java 2D
• Cast the Graphics class to Graphics2D
– Graphics2D g2 = (Graphics2D) g;
• Set up the stroke if desired
– setStroke(new BasicStroke(widthAsFloat));
• Set up any Color, GradientPaint, or TexturePaint
– setPaint(Color.blue);
– setPaint(blueToPurpleGradient);
– setPaint(texture);
• Create a geometric shape
– Line2D line2D = new Line2D.Double(0.0,0.0,100.0,100.0);
• Draw the outline of a geometric shape
– draw(line2d);
• Fill a geometric shape
– fill(rectangle2d);
Georgia Institute of Technology
Drawing Lines Exercise
• Create a new method for
adding two wide crossed
lines to a picture
– Using a passed color
– Using a passed line width
• Set up the stroke to make
the lines thicker
– g2.setStroke(new
BasicStroke(width));
– Draw the lines
Georgia Institute of Technology
Clipping
• You can even create text
outlines that show an
image through them
– Like a stencil
• In the picture on the right
we are showing the
image through the letters
of the message
Georgia Institute of Technology
Clip To Message Method
public void clipToMessage(String message)
{
Image image = this.getImage();
int width = this.getWidth();
// get a graphics context from this picture
Graphics graphics = getGraphics();
Graphics2D g2 = (Graphics2D) graphics;
// create an outline from the message
FontRenderContext frc = g2.getFontRenderContext();
Font f = new Font("Helvetica", 1, width/10);
String s = new String(message);
TextLayout tl = new TextLayout(s, f, frc);
AffineTransform transform = new AffineTransform();
Shape outline = tl.getOutline(null);
Rectangle r = outline.getBounds();
transform = g2.getTransform();
transform.translate(width/2-(r.width/2), this.getHeight()/2+(r.height/2));
g2.transform(transform);
g2.setColor(Color.black);
g2.draw(outline);
// draw the current image clipped by the message outline
g2.setClip(outline);
g2.drawImage(image, r.x, r.y, r.width, r.height, null);
}
Georgia Institute of Technology
Movies
• Movie projectors show a
series of still images
(frames)
– Some number of frames
per second (24)
• We see continuous
motion due to
– Persistence of vision
• Why we don’t notice when
we blink
Georgia Institute of Technology
Animation
• An animation has at least one thing moving in it
• Two ways
– Show still pictures one after the other
• Flip-book animation
• Used in movies
– Draw something differently over time
Georgia Institute of Technology
Copying a Picture in a Loop
• One way to do an
animation is to copy a
picture to another picture
in a loop
– Each time start with the
original picture
– Copy the second picture to
a different location each
time
– Then repaint the picture
Georgia Institute of Technology
Show Turtle Movie Method
/**
* Method to show a turtle crawling across the beach
*/
public static void showTurtleMovie()
{
Picture beachPicture = new Picture(Picture.getMediaPath("beach-smaller.jpg"));
Picture turtlePicture = new Picture(Picture.getMediaPath("greenTurtleSmall.jpg"));
Picture viewedPicture = new Picture(beachPicture.getWidth(),
beachPicture.getHeight());
int maxX = beachPicture.getWidth() - turtlePicture.getWidth();
// loop moving turtle across the beach
for (int i=0; i < maxX; i+=5)
{
viewedPicture.copy(beachPicture,0,0,
beachPicture.getWidth()-1,beachPicture.getHeight()-1,0,0);
viewedPicture.copy(turtlePicture,0,0,
turtlePicture.getWidth()-1,turtlePicture.getHeight()-1,
i,viewedPicture.getHeight() - 100);
viewedPicture.repaint();
}
}
Georgia Institute of Technology
Turtle Movie Exercise
• Modify the showTurtleMovie method to call a
new method
– copyNonWhitePixels(sourcePicture,startX,startY,
endX,endY,targetStartX,targetEndX);
• Write the method
– copyNonWhitePixels which will copy a source picture
pixel if it isn’t near white
• colorDistance(Color.white) > 100
Georgia Institute of Technology
Summary
• Use a Graphics object to draw simple shapes
– Lines, ovals, polygons, arcs, strings
• Set the color before you draw
• Set the font before you draw strings
• Use a Graphics2D object for more complex
drawing
– Curves, gradients, textures, clipping
• You can create an animation by changing what
you draw over time
Georgia Institute of Technology
Download