Download Week 10—11/08/11) Graphics

Document related concepts

Stereo photography techniques wikipedia , lookup

Indexed color wikipedia , lookup

Video card wikipedia , lookup

Stereoscopy wikipedia , lookup

Spatial anti-aliasing wikipedia , lookup

Hold-And-Modify wikipedia , lookup

Graphics processing unit wikipedia , lookup

Rendering (computer graphics) wikipedia , lookup

Image editing wikipedia , lookup

Apple II graphics wikipedia , lookup

Waveform graphics wikipedia , lookup

Molecular graphics wikipedia , lookup

Framebuffer wikipedia , lookup

Tektronix 4010 wikipedia , lookup

Stereo display wikipedia , lookup

BSAVE (bitmap format) wikipedia , lookup

2.5D wikipedia , lookup

Transcript
November 3, 2009
Chapter 10--Graphics
The fun stuff in Java
Jim Burns
ISQS 6337
Overview


paint() and repaint() methods
drawString() method to draw Strings using various
fonts and colors

Graphics and graphics2D objects

Draw lines and shapes

Use fonts and methods

Draw with Java 2D graphics

Add sound, images, simple animation
The JDemoPaint JApplet
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.*;
Public class JDemoPaint extends JApplet implements ActionListener {
Container con = getContentPane();
Jbutton pressButton = new JButton (“Press”);
Public void init() {
con.setLayout(new FlowLayout());
con.add(pressButton);
pressButton.addActionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
System.out.println(“In paint method”);
}
Public void actionPerformed(ActionEvent e)
{
repaint();
}
}
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.*;
Public class JDemoPaint extends JApplet
implements ActionListener {
Container con = getContentPane();
Jbutton pressButton = new JButton
(“Press”);
Public void init() {
con.setLayout(new FlowLayout());
con.add(pressButton);
pressButton.addActionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
System.out.println(“In paint method”);
}
Public void actionPerformed(ActionEvent e)
{
repaint();
}
}
The paint() Method


When you don’t provide this method, Java uses its default
paint() method
The method header is
 public



void paint(Graphics g)
The method requires a Graphics object argument
You usually don’t call the paint() method directly; instead,
you call the repaint() method
The repaint() method is called by Java, when it needs to
update a window, or you can call it yourself
Explanation of the above




In the above, JDemoPaint gets a content pane and a
JButton
An explicitly provided paint() method contains the
statements
super.paint(g);
System.out.println(“In paint method”);
The first statement above, super.paint(g); is not needed
for this simple paint() method, but omitting it will cause
errors in more complicated paint() methods
This paint() method overrides the Java-provided paint()
method.
Required HTML document
<html>
<object code = “JDemoPaint.class” width = 100
height = 100>
</object>
</html>
Execution

When the user clicks the pressButton in the applet,
the actionPerformed() method calls the repaint()
method and the repaint() method calls the update()
method, which then calls the paint() method, causing
a new message ‘In paint method’ to appear on the
command line
Using the drawString() Method to Draw
Strings



Allows you to draw a string in a JApplet window—
requires three args—a string, an x-axis coordinate,
and a y-axis coordinate
The lower-left corner of the drawString component
is placed at the coordinate position
The drawString() method is a member of the
Graphics class, so you need to use a Graphics
object to call it, just like you did for paint()
An example of usage of drawString()
First, you include a paint() method:
public void paint(Graphics brush)
 Then you can draw a String within your paint()
method by use of
brush.drawString(“Hi”, 50, 80);

Using the setFont() Method
Improves the appearance of strings drawn using Graphics
objects
 Requires a Font object that you create with a statement
such as
Font someFont = new Font(“TimesRoman”, Font.BOLD, 16);
 Then, you instruct a Graphics object to use the font by
using it as the argument in a setFont() method
 Assume a Graphics object named artist and a Font object
named someFont, the font is set to someFont with the
following:
 Artist.setFont(someFont);

Creating Graphics and Graphics2d
Objects



While the paint() method automatically creates a
Graphics object that is passed to it, you can
instantiate your own Graphics or Graphics2D
objects.
The actionPerformed() method does not supply you
with a Graphics object
So you can create your own
Public void actionPerformed(ActionEvent e)
{
graphics draw = getGraphics();
draw.drawString(“You clicked the button!”, 50,
100);
}
The above method instantiates a Graphics object
named draw.
The getGraphics() method provides the draw object
with Graphics capabilities. The draw object can
employ setFont(), setColor()
Some details about the Graphics class





This is an abstract class, so you cannot actually
create a new object in this class using the Graphics()
constructor
Instead, you must use the getGraphics() method
You are not allowed to create objects of abstract
classes
Container is also an abstract class
Image is another abstract class
Drawing Lines and Shapes

You can use the drawLine() method to draw a
straight line between any two points on the screen
 pen.drawLine(10,

10, 100, 200);
An identical line would be created by
 pen.drawLine(100,


200, 10, 10);
because you can start from either line.
The following statement draws a short, wide
rectangle that begins at position 20, 100 and is
200 pixels wide by 10 pixels tall
 drawRect(20,
100, 200, 10);
More Graphics Methods



The fillRect() method draws a solid, filled rectangle
Both drawRect() and fillRect() methods require four
arguments—the first two arguments represent the xand y- coordinates of the upper-left corner of the
rectangle, while the last two arguments represent the
width and height of the rectangle
Both drawRect() and fillRect() fill with the current fill
color

import javax.swing.*;

import java.awt.*;

public class JDemoRectangles extends JApplet

{

Container con = getContentPane();

public void init()

{

con.setBackground(Color.BLUE);

con.setLayout(new FlowLayout());

}

public void paint(Graphics gr)

{

super.paint(gr);

gr.setColor(Color.RED);

gr.fillRect(20, 20, 120, 120);

gr.clearRect(49, 40, 50, 50);

}

}
The following JApplet draws rounded
rectangles
import javax.swing.*;
import java.awt.*;
public class JDemoRoundRectangles extends JApplet
{
public void paint(Graphics gr)
{
super.paint(gr);
int x = 20;
int y = 20;
int width = 80, height = 80;
gr.drawRoundRect(x, y, width, height, 0, 0);
x += 100;
gr.drawRoundRect(x, y, width, height, 20, 20);
x += 100;
gr.drawRoundRect(x, y, width, height, 40, 40);
x += 100;
gr.drawRoundRect(x, y, width, height, 80, 80);
}
}
Drawing Ovals



It is possible to draw an oval using the
drawRoundRect() or the fillRoundRect() methods, but
it is usually easier to use the drawOval() and
fillOval() methods
These methods draw ovals using the same four
arguments that rectangle methods use
Suppose you create a graphics object named tool
tool.drawRect(50, 50, 100, 60);
tool.drawOval(50, 50, 100, 60);

Draws an oval within a rectangle
halfArc.drawArc(x, y, w, h, 0, 180);
halfArc.drawArc(x, y, w, h, 180, -180);
solidArc.fillArc(10, 50, 100, 100, 20, 320);
solidArc.fillArc(200, 50, 100, 100, 340, 40);
The latter creates a solid arc of 300 degrees
And a pie wedge of 60 degrees
Drawing Arcs


You can draw an arc using the Graphics drawArc()
method
You must provide six arguments
 The
x-coordinate of the upper-left corner of the
imaginary rectangle
 The y-coordinate of the same corner
 The width of the imaginary rectangle
 The height of the same imaginary rectangle
 The beginning arc position
 The arc angle
Creating Three-dimensional
rectangles



Instead of the drawRect() method, the draw3DRect()
method is used that appears to have ‘shadowing’ on
two of its edges
The effect is that of a rectangle that is slightly
raised or slightly lowered
draw3DRect() takes five arguments instead of the
usual 4 required by drawRect(). The fifth argument
is a boolean value that is true if you want the raised
effect and false if you want the lowered value
import javax.swing.*;
import java.awt.*;
public class JDemo3DRectangles extends JApplet
{
public void paint(Graphics gr)
{
super.paint(gr);
int width = 60, height = 80;
gr.setColor(Color.PINK);
gr.fill3DRect(20, 20, width, height, true);
gr.fill3DRect(120, 20, width, height, false);
}
}
Creating Polygons




You can use drawPolygon() method to create complex shapes;
this is easier than a sequence of calls to drawLine() method
The drawPolygon() method requires three arguments: two
integer arrays and a single integer
The first integer array holds x-coordinate positions, while the
second integer array holds y-coordinate positions. These
positions represent points that are connected to form the
polygon.
The third integer argument is the number of pairs of points you
want to connect.
Import javax.swing.*;
Import java.awt.*;
Public class JStar extends Japplet
{
public void paint(Graphics gr)
{
super.paint(gr);
int xPoints[] = {42, 52, 72, 52, 60, 40, 15,
28, 9, 32, 42};
int yPoints[] = {38, 62, 68, 80, 105, 85, 102,
75, 58, 60, 38};
gr.drawPolygon(xPoints, yPoints,
xPoints.length);
}
Copying an Area


To copy a graphics image to another location, you
can use the copyArea() method to copy any
rectangular area to a new location
The copyArea() method requires six arguments:
 The
x- and y-coordinates of the upper-left corner of
the area to be copied
 The width and height of the area to be coied
 the horizontal and vertical displacement of the
destination of the copy

gr.copyArea(0, 0, 20, 30, 100, 50);
Learning more about Fonts and
Methods

As you add more components in your JApplet,
positioning becomes increasingly important. If your
user’s computer does not have the requested font
loaded, Java chooses a default replacement font,
so you are never completely certain how your
output will look. You can discover the fonts that are
available on your system by using getAllFonts()
method. This is part of the GraphicsEnvironment
class defined in the java.awt package. The
getAllFonts() method returns an array of String
objects.
import javax.swing.*;
import java.awt.*;
public class JFontList extends JApplet
{
public void paint(Graphics gr)
{
super.paint(gr);
int i, x, y = 10;
final int VERTICAL_SPACE = 15;
final int HORIZONTAL_SPACE = 180;
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = ge.getAvailableFontFamilyNames();

for (i = 0; i < fontnames.length; i += 4)
{
x = 10;
gr.drawString(fontnames[i], x, y);
if(i+1 < fontnames.length)
gr.drawString(fontnames[i+1], x +=
HORIZONTAL_SPACE, y);
if(i+2 < fontnames.length)
gr.drawString(fontnames[i+2], x +=
HORIZONTAL_SPACE, y);
if(i+3 < fontnames.length)
gr.drawString(fontnames[i+3], x +=
HORIZONTAL_SPACE, y);
y = y + VERTICAL_SPACE;
}
}
}
Discovering Screen Statistics using the
Toolkit class



In order to determine the best font size to use, your
program needs to know what the screen resolution
and screen size are.
To find these you can use the getScreenResolution()
and getScreenSize() methods, both of which are
part of the Toolkit class
You can create a Toolkit object and get the screen
resolution using the following code:
Toolkit tk = Toolkit.getDefaultToolkit();
Int resolution = tk.getScreenResolution();
The Dimension class


Can be used to determine the width and height of a
user interface component, such as a JApplet or a
JButton.
The Dimension class has three constructors:
 The
Dimension() method creates an instance of
Dimension with a width of zero and a height of zero
 The Dimension(Dimension d) creates an instance of
Dimension whose width and height are the same as for
the specified dimension
 The Dimension(int width, int height) constructs a
Dimension and initializes it to the specified width and
height
The getScreenSize() method ….




Is a member of the Toolkit class
Returns an object of type Dimension, which specifies
the width and height of the screen in pixels.
This is useful to set the coordinates for the position,
width, and height of a window
Consider the following code which stores the width
and height of a screen in separate variables:
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screen = tk.getScreenSize();
Int width = screen.width;
Int height = screen.height;
Discovering Font Statistics

Typesetters measure the height of every font in
three parts:
 Leading—the amount of space between baselines
 Ascent—is the height of an uppercase character
from a baseline to the top of the character
 Descent—the part of characters that ‘hang below’
the baseline, such as the tails on the lowercase
letters g and j
 The height of a font is the sum of the leading,
ascent and descent
There are methods to get font statistics
To do so you use the graphics class, and create an object
from that class
 The following methods are available…
public int getLeading(0
public int getAscent(0
public int getDescent()
public int getHeight()
Each of these methods returns an integer value representing
the font size in points (one point measures 1/72 of an inch)

Drawing with Java 2D Graphics




Earlier, drawing operations were called using a
Graphics object
In addition, you can call drawing operations using a
Graphics2D object
The advantage of Graphics2D is the higher-quality, twodimensional (2D) graphics, images, and text it provides.
Features of 2D classes include:
 Fill patterns, such as gradients
 Strokes that define the width and style of a drawing
stroke
 Anti-aliasing, for smoother graphics
Here’s how you get Java 2D graphics
The Graphics2D object is produced by casting or
converting and promoting, a Graphics object. For
example, in a paint() method that automatically
receives a Graphics object, you can cast the object
to a Graphics2D object using the following:
Public void paint(Graphics pen)
{
Graphics2D newpen = (Graphics2D)pen;
Specifying the Rendering Attributes
The first step is to specify how a drawing object is
to be rendered
 For example, what color is to be used?
gr2D.setColor(Color.BLACK);
 Will set the color of the object to black

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class JGradient extends JApplet
{
public void paint(Graphics gr)
{
super.paint(gr);
int x = 10, y = 20, x2 = 180, y2 = 100;
Graphics2D gr2D = (Graphics2D)gr;
gr2D.setPaint(new GradientPaint(x, y, Color.LIGHT_GRAY,
x2, y2, Color.DARK_GRAY, false));
gr2D.fill(new Rectangle2D.Double(x, y, x2, y2));
x = 210;
gr2D.setPaint(new GradientPaint(x, y, Color.LIGHT_GRAY,
x2, y2, Color.DARK_GRAY, true));
gr2D.fill(new Rectangle2D.Double(x, y, x2, y2));
}
}
Setting a Drawing Stroke



All lines in non-2D graphics operations are drawn
as solid, with square ends and a line width of one
pixel.
With 2D methods, the drawing line is a stroke, which
represents a single movement as if you were using a
drawing tool
The following code creates a rectangle with a very
wide stroke or border
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class JStroke extends JApplet
{
public void paint(Graphics gr)
{
super.paint(gr);
Graphics2D gr2D = (Graphics2D)gr;
BasicStroke aStroke = new BasicStroke(15.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
gr2D.setStroke(aStroke);
gr2D.draw(new Rectangle2D.Double(10, 20, 100, 100));
}
}
Creating objects to Draw

You can draw…
 Lines
 Rectangles
 Ovals
 Arcs
 Polygons
 2D
methods are available for all of these
Adding Sound, Images and Animation
to JApplets




Java 2D supports sound using methods from the
Applet class
Formats include Windows Wave file format (.wav),
Sun audio file format (.au) and Music and Instrument
Digital Interface file format (.midi or .mid)
The simplest way to retrieve and play a sound is to
use the play() method of the Applet class
The play() method retrieves and plays the sound as
soon as possible after it is called
Adding Images (likenesses of people
or things)




Java supports GIT (Graphics Image Format), JPEG (Joint
Photographic Experts Group) and PNG (Portable
Network Graphics—which is lossless form—more flexible
and dense than GIF)
The Image class provides most of Java’s image
capabilities
This class loads images that have been stored in one of
the allowed Image formats
It is an abstract class so you cannot create any objects
but you can use it as an interface from which you can
inherit
More about adding Images


Because image is abstract, you must create Image
objects indirectly using the getImage() method
Here is how you declare an image:
 Image

eventLogo;
Here is how you create and load an Image:
 eventLogo
= getImage(getCodeBase(), “event.gif”);
 The first argument gets the reference (starting address
of the image) and the second argument passes the
name of the image
Displaying an image



You must use the applet paint() method to display
Image object images.
Then you use the drawImage() method to draw the
image on the applet.
the drawImage() method is a graphics method that
uses the following four arguments
 The
first argument is a reference to the Image object in
which the image is stored
 The second argument is a the x-coordinate
 The third argument is the y-coordinate
 The fourth argument is a reference to an Image
Observer object
ImageObserver Object…



Can be any object that implements the image
observer interface
Usually the ImageObserver object is the object on
which the image appears—in this case, the JApplet.
For example, the code to display the eventlogo
image in the upper-left corner of the JApplet is as
follows:
 g.drawImage(eventLogo,
0, 0, this);
 There is also a six-argument version of drawImage()
that can be used to output a scaled image
import java.awt.*;
import java.applet.*;
import javax.swing.*;
public class JEventImage extends JApplet
{
Image eventLogo;
public void init()
{
eventLogo = getImage(getCodeBase(),"event.gif");
public void paint(Graphics g)
{
super.paint(g);
// Draw image at its natural size 300 X 40
g.drawImage(eventLogo, 0, 0, this);
// Draw the image scaled - twice as large
g.drawImage(eventLogo, 0, 50, 600, 80, this);
//Draw the image 100 pixels narrower than the JApplet
// and 120 pixels shorter
g.drawImage(eventLogo, 0, 120, (getWidth() - 100),
(getHeight() - 120), this);
} }
}
Using ImageIcons





You can use the ImageIcon class to create images in
your applications and applets.
In general working with the ImageIcon class is easier
than working with the Image class.
You can use all Image methods with an ImageIcon,
plus many additional methods.
Unlike the Image class, you can create ImageIcon
objects directly
Also, unlike the Image class, you can place an
ImageIcon on a Component, such as a JPanel, a
JLabel, or JButton
More on using ImageIcon(s)



ImageIcon objects are real objects
Image objects are abstract objects
For example the following code creates a JButton
that contains a picture of an arrow:
ImageIcon arrowPicture = new ImageIcon(“arrow.gif”);
JButton arrowButton = new JButton(arrowPicture);
To display an ImageIcon…


You use the paintIcon() method to display ImageIcon
images
This method has four arguments:
 The
first argument is a reference to the Component on
which the image appears—this in the following example
 The second argument is a reference to the Graphics
object used to render the image—g in the following
example
 The third argument is the x-coordinate for the upper-left
corner of the image
 The fourth argument is the y-coordinate for the upperleft corner of the image
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JBear extends JApplet implements ActionListener
{
private ImageIcon image = new ImageIcon("bear.gif");
private JButton closerButton = new JButton("Oh my!");
private int width, height;
Container con = getContentPane();
public void init()
{
con.setLayout(new FlowLayout());
closerButton.addActionListener(this);
con.add(closerButton);
width = image.getIconWidth();
height = image.getIconHeight();
}
public void actionPerformed(ActionEvent event)
{
width = width * 2;
height = height * 2;
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image.getImage(), 0, 0, width, height, this);
}
}
The end
Project Description
Objective
 Add your objective here
Results
 Add your results here
Procedure / Methodology
Add your procedure here
Key Assumptions
 Add your assumptions here
Key Findings / Results 1
90
80
70
60
50
First
Second
Third
40
30
20
10
0
Test 1
Test 2
Test 3
Test 4
Key Findings / Results 2
Item 1
Item 2
Item 3
Item 4
Key Findings / Results 3
Run
number Description
Result A Result B
1
Condition A
True
True
2
Condition B
True
False
3
Condition C
False
False
Conclusion
Add your conclusion here
Questions
&
Discussion