0% found this document useful (0 votes)
5 views

Computer - Graphics 2

MySQL

Uploaded by

ms4741100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Computer - Graphics 2

MySQL

Uploaded by

ms4741100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Outline

 Introduction.
CSE 201  Graphics Contexts and Graphics Objects.
 Color Control.
INTRODUCTION TO COMPUTING II  Font Control.
 Drawing Lines, Rectangles and Ovals.
CHAPTER – 18  Drawing Arcs.
 Drawing Polygons and Polylines.
GRAPHICS IN JAVA
 The Java 2D API (Application Programming Interface).
 Java 2D Shapes.
1 2
Introduction to Computer Graphics Cont…
• Computer graphics: generating 2D images of a 3D world Applications of
represented in a computer. Computer Graphics
1. Entertainment: Entertainment
• Main tasks in Graphics:

The Visible Human Project


animated movies, etc.
• modeling: (shape) creating and representing the geometry of
objects in the 3D world. 2. Medical Visualization
• rendering: (light, perspective) generating 2D images of objects. 3. Educational Training Training
• animation: (movement) describing how objects change in time. 4. Game Modeling &
• Representations in Graphics: Simulation
Medical
• Vector Graphics: Image is represented by 5. Graphical User Interfaces Visualization
continuous geometric objects: lines, curves,
etc. E.g., PowerPoint, CorelDraw, SVG, ... (GUI)
• Raster Graphics: Image is represented as 6. Computer Aided Design
a rectangular grid of colored pixels… generic
& realistic images. E.g., Paint, PhotoShop, ... (CAD)
y-axis (512, 384, Games & Simulation
0)
7. Scientific Visualization
• Coordinate System : x-axis
CAD
• World Coordinates: Center is (0,0) z-axis (512, -384, 0)
• Screen Coordinates: Upper-left corner is (0,0) (0, 0, 0) in world coordinates
(512,384,0) in real coordinates
3 •… Scientific
Visualization
GUI 4
Cont… Cont…
Other tasks in Graphics: Edge • Using the Graphics Class in Java
• Image processing techniques Detection • paint() or paintComponent() is passed a reference
• Edge Detection to a Graphics object.
• Image De-noising Image • A Graphics object is a device-independent interface to the
• Object Detection De-noising
computer's graphics display.
•…
• Geometric Transformations • Most of its methods are concerned with drawing shapes
• Translation: moving an item from one location to (filled and unfilled), and managing fonts and colours .
another, e.g., moving thru a room or landscape. Translation
• paint() or paintComponent() sends Graphics object:
• Rotation: changing the orientation of an item at a • the drawOval() message, to draw each point .
given location, e.g., spinning around. • the drawLine() message, to draw the straight line .
• Scaling: changing the size of an item as it appears
on screen, e.g., item gets larger or smaller. Rotation
• Some Graphics Methods:
• Clipping: knowing where to stop drawing an item • drawString()
because it partially extends beyond the screen. • drawOval(), fillOval()
• drawRect(), fillRect(), clearRect()

Scaling
drawRoundRect(), fillRoundRect()
• More advanced operations: Hidden surface • draw3DRect(), fill3DRect()
algorithms, Representing 3D shapes, Displaying depth • drawArc(), fillArc()
relationships, Shading, reflection, ambient lighting.. etc… • drawPolygon(), fillPolygon()
5 • drawPolyline() 6
Cont…
• Put your own graphics on the screen:
1. Create your own paintable widget Make a subclass of JPanel, a widget
that can be added to a frame, and
2. Put the widget on the frame override the paintComponent() method
3. Display it g is a Graphic object; actual drawing
--------------------------------------------
surface that mapped to the real display,
import java.awt.*; and is handed to you by the system
import javax.swing.*;
class MyDrawPanel extends JPanel { paintComponent() or paint() is called
Graphics
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
by system when painting the widget

Draw a rectangle with orange color


In
g.fillRect(20,50,100,100);
} Java
public static void main(String[] args) {
MyDrawPanel dP=new MyDrawPanel();
JFrame jF = new JFrame("Graphics");
jF.add(dP);
jF.setSize(250,250);
jF.setVisible(true);
}
}

Example-1: Draw a rectangle in orange color 7 8


Graphics Context and Objects Cont…
• A GUI component is an object that can be represented
visually on the computer screen and can be acted upon • java.awt.Graphics is the abstract superclass for
by a human user. all graphics context objects in Java. You can use its
• Examples: windows, buttons, combo boxes, scroll bars, etc. methods to get and set the data within a graphics
• In Java, such an object must be an instance of the class context.
java.awt.Component or its many subclasses. • Enables drawing on screen. Has methods for drawing, font
manipulation, etc.
• Rendering is the process of transforming the GUI • Graphics is an abstract class!
component’s internal data into a visual image. • Cannot instantiate objects.
• In Java, a graphics context object holds the data needed to • Implementation hidden - more portable.
do this transformation. Such data includes:
• The component’s color.
• The component’s font.
• The transform mapping is used to convert component
coordinates into pixel positions on the display device.
9 10
Cont… Color Control
• The Component Class •Class Color
• Superclass for many classes in java.awt package • Defines methods and constants for manipulating colors.
• Method paint() takes Graphics object as an argument. • Colors created from red, green, and blue (RGB) components.
• RGB value:
• paint()often called in response to an event.
• 3 integers from 0 to 255 each, or 3 floating point values
• repaint()calls update(), which forces a paint() from 0 to 1.0 each.
operation. • Larger the value, more of that color.
• update() rarely called directly!
• Color methods getRed(), getGreen(), getBlue()
• Sometimes overridden to reduce "flicker"
Headers:
return an integer between 0 and 255 representing
public void repaint() amount.
public void update(Graphics g)
• Graphics method setColor() takes Color object
and sets the drawing color.
• Method getColor() gets / returns current color
Note:- In this lecture, we’ll focus on paint() method. 11
setting. 12
Cont… Cont…
import javax.swing.*; Example-2: Using JColorChooser
 Component JColorChooser import java.awt.*;
import java.awt.event.*;
• The JColorChooser class is used public class ColorChooserExample
to create a color chooser dialog extends JFrame implements ActionListener {
JFrame f;
box so that user can select any JButton b;
color. It inherits JComponent class. JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
• Method showDialog(Component cmp, String title, Color initColor) b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
- First argument: reference to parent Component (window ta=new JTextArea();
ta.setBounds(10,10,300,200);
from which dialog being displayed) b.addActionListener(this);
f.add(b);f.add(ta);
Modal dialog - user cannot interact with other dialogs while active. f.setLayout(null);
- Second argument: String for title bar. f.setSize(400,400);
f.setVisible(true);
- Third argument: Initial selected color. }
f.setDefaultCloseOperation(EXIT_ON_CLOSE);

• showDialog() returns a Color object public void actionPerformed(ActionEvent e){


Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
 Class Container ta.setBackground(c);
}
Method setBackground() - takes Color object
public static void main(String[] args) {
- Sets background color. 13 new ColorChooserExample(); 14
}
}
Cont… Cont…
Example-3: Using colors Outline: // set new drawing color using static Color objects Outline:
import java.awt.*; g.setColor( Color.blue );
import javax.swing.*; import g.fillRect( 25, 75, 100, 20 ); define paint()
import java.awt.event.*; g.drawString( "Current RGB: " + g.getColor(), 130, 90 );

public class ShowColors extends JFrame { // display individual RGB values


public ShowColors() { Color c = Color.magenta;
super( "Using colors" );
Class definition g.setColor( c );
setSize( 400, 130 ); g.fillRect( 25, 100, 100, 20 );
setVisible(true); // show(); g.drawString( "RGB values: " + c.getRed() + ", " +
} c.getGreen() + ", " + c.getBlue(), 130, 115 );
}
public void paint( Graphics g ) {
// set new drawing color using integers public static void main( String args[ ] ) {
ShowColors app = new ShowColors();
main() method
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
define paint() }
}
// set new drawing color using floats Program Output
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );

15 16
Font Control Cont…
• Methods
• Class Font • isPlain()
• getStyle()
 The Font class states fonts, which are used to render text in a • Returns the style of this Font. • Indicates whether or not this Font object's
visible way. style is PLAIN.
• getSize()
 Constructor: creates a new Font from the specified font, and it • isBold()
• Returns the point size of this Font.
takes three arguments: • Indicates whether or not this Font object's
public Font( String name, int style, int size) • getName() style is BOLD.
• name: any font supported by system (Serif, Monospaced) • Returns the logical name of this Font.
• isItalic()
• style: constants FONT.PLAIN, FONT.ITALIC, FONT.BOLD • getFamily() • Indicates whether or not this Font object's
– Combinations: FONT.ITALIC + FONT.BOLD • Returns the family name of this Font. style is ITALIC.
• size: measured in points (1/72 of an inch) • setFont(Font f)
• getFont()
 Use similar to Color • Is used to set the graphics current font to
Returns a Font object from the system
 g.setFont(fontObject); properties list.
the specified font.

17 18
Cont… Cont…
Example-4: Using fonts Outline:
Outline: // set current font to SansSerif (Helvetica),
import java.awt.*; // plain, 14pt and draw a string
import javax.swing.*; import g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) ); define paint()
import java.awt.event.*; g.drawString( "SansSerif 14 point plain.", 20, 90 );

public class Fonts extends JFrame { // set current font to Serif (times), bold/italic,
public Fonts() { // 18pt and draw a string
super( "Using fonts" ); g.setColor( Color.red );
setSize( 420, 125 );
Class definition g.setFont(new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
setVisible(true); // show(); g.drawString( g.getFont().getName() + " " +
} g.getFont().getSize() + " point bold italic.", 20, 110 );
}
public void paint( Graphics g ) {
// set current font to Serif (Times), bold, 12pt public static void main( String args[] ) {
Fonts app = new Fonts();
main() method
// and draw a string
}
g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
g.drawString( "Serif 12 point bold.", 20, 50 );
define paint() }

// set current font to Monospaced (Courier), Program Output


// italic, 24pt and draw a string
g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
g.drawString( "Monospaced 24 point italic.", 20, 70 );
19 20
Cont… Cont…
• Class FontMetrics • FontMetrics (and Graphics) methods
• Has methods for getting font metrics: • getAscent()
• Determines the font ascent of the Font described by this FontMetrics object.
• g.getFontMetrics() • getDescent()
• Determines the font descent of the Font described by this FontMetrics object
- returns FontMetrics object
• getLeading()
• Determines the standard leading of the Font described by this FontMetrics object.
leading
• getHeight()
height

Xy1 ascent

baseline
descent
• Gets the standard height of a line of text in this font.
• getFontMetrics()
• Gets the font metrics of the current font.

• getFontMetrics(Font f)

• ascent is the distance this string extends above the baseline. • Gets the font metrics for the specified font.
• descent is the distance this string descends below the baseline. 21 22
Cont… Cont…
Example-5: Using FontMetrics Outline: Font font = new Font( "Serif", Font.ITALIC, 14 ); Outline:
fm = g.getFontMetrics( font );
import java.awt.*;
import
g.setFont( font ); define paint()
import java.awt.event.*; g.drawString( "Current font: " + font, 10, 130 );
import javax.swing.*; g.drawString( "Ascent: " + fm.getAscent(), 10, 145 );
g.drawString( "Descent: " + fm.getDescent(), 10, 160 );
public class Metrics extends JFrame { g.drawString( "Height: " + fm.getHeight(), 10, 175 );
public Metrics() { g.drawString( "Leading: " + fm.getLeading(), 10, 190 );
super( "Demonstrating FontMetrics" ); Class definition }
setSize( 510, 210 );
setVisible(true); // show(); public static void main( String args[] ) {
} Metrics app = new Metrics(); main() method
}
public void paint( Graphics g ) { }
g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) );
FontMetrics fm = g.getFontMetrics();
g.drawString( "Current font: " + g.getFont(), 10, 40 ); define paint()
g.drawString( "Ascent: " + fm.getAscent(), 10, 55 );
g.drawString( "Descent: " + fm.getDescent(), 10, 70 ); Program Output
g.drawString( "Height: " + fm.getHeight(), 10, 85 );
g.drawString( "Leading: " + fm.getLeading(), 10, 100 );

23 24
Note: Program Output may differ on different computers
Drawing Lines, Rectangles and Ovals Cont…
• Graphics methods for drawing shapes: • Graphics methods for drawing shapes (Cont.)
• drawLine(x1, y1, x2, y2)  fill3DRect(x, y, width, height, raised)
• Draws a Line from (x1, y1) to (x2, y2). • Paints a 3-D highlighted rectangle filled with the current color.
• drawRect(x1, y1, width, height)  drawRoundRect(x, y, width, height, arcWidth, arcHeight)
• Draws a rectangle with upper left corner (x1,y1).
• Draws rectangle with rounded corners. See diagram next slide.
• fillRect(x1, y1, width, height)
 fillRoundRect(x, y, width, height, arcWidth, arcHeight)
• As above, except fills rectangle with current color.
• Fills the specified rounded corner rectangle with the current color.
• clearRect(x1, y1, width, height)  drawOval(x, y, width, height)
• As above, except fills rectangle with background color • Draws oval in bounding rectangle (see diagram).
• draw3DRect(x1, y1, width, height, isRaised) • Touches rectangle at midpoint of each side.
• Draws 3D rectangle, raised if isRaised is true, else lowered.
 fillOval(x, y, width, height)
• Fills an oval bounded by the specified rectangle with the current color.

25 26
Cont… Cont…
Example-6: Drawing Lines, Rectangles and Ovals Outline:
(x, y) import java.awt.*;
drawRoundRect() parameters import java.awt.event.*; import
import javax.swing.*;
arc height
public class LinesRectsOvals extends JFrame {
arc width
private String s = "Using drawString!";
height Class definition
public LinesRectsOvals() {
super( "Drawing lines, rectangles and ovals" );
setSize( 400, 165 );
setVisible(true); // show();
}
width define paint()
(x, y) public void paint( Graphics g ) {
g.setColor( Color.red );
g.drawLine( 5, 35, 350, 35 );
drawOval() parameters
g.setColor( Color.blue );
height g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );
g.setColor( Color.cyan );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
width 27 28
Cont… Drawing Arcs
•Arc
g.setColor( Color.yellow );
Outline:
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false ); define paint() • Portion of an oval.
g.setColor( Color.magenta ); • Measured in degrees.
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 ); • Starts at a starting angle and sweeps the number of degrees
} specified by arc angle.
public static void main( String args[] ) {
main() method • Positive – counterclockwise.
}
LinesRectsOvals app = new LinesRectsOvals(); • Negative – clockwise.
}
• When drawing an arc, specify bounding rectangle for
an oval.
Program Output • drawArc(x, y, width, height, startAngle, arcAngle)
- is used to draw a circular or elliptical arc.
• fillArc(x, y, width, height, startAngle, arcAngle)
- as above but draws a solid arc (sector).
29 30
Cont… Cont…
Example-7: Drawing Arcs Outline: // start at 0 and sweep -270 degrees
import java.awt.*; g.setColor( Color.yellow );
Outline:
import javax.swing.*; g.drawRect( 185, 35, 80, 80 );
import
import java.awt.event.*; g.setColor( Color.black ); define paint()
g.drawArc( 185, 35, 80, 80, 0, -270 );
public class DrawArcs extends JFrame { // start at 0 and sweep 360 degrees
public DrawArcs() { g.fillArc( 15, 120, 80, 40, 0, 360 );
super( "Drawing Arcs" ); Class definition // start at 270 and sweep -90 degrees
setSize( 300, 170 ); g.fillArc( 100, 120, 80, 40, 270, -90 );
setVisible(true); // show(); // start at 0 and sweep -270 degrees
} g.fillArc( 185, 120, 80, 40, 0, -270 );
}
public void paint( Graphics g ) {
// start at 0 and sweep 360 degrees public static void main( String args[] ) {
g.setColor( Color.yellow );
define paint() DrawArcs app = new DrawArcs(); main() method
g.drawRect( 15, 35, 80, 80 ); }
g.setColor( Color.black ); }
g.drawArc( 15, 35, 80, 80, 0, 360 );
// start at 0 and sweep 110 degrees
g.setColor( Color.yellow ); Program Output
g.drawRect( 100, 35, 80, 80 );
g.setColor( Color.black );
g.drawArc( 100, 35, 80, 80, 0, 110 );
31 32
Drawing Polygons and Polylines Cont…
• Polygon - multisided shape. • Methods of class Polygon (Cont.):
• drawPolygon(myPolygon)
• Polyline - series of connected points.
• Draws specified closed polygon.
• Methods of class Polygon: • fillPolygon(xPoints[], yPoints[], points)
• drawPolygon(xPoints[], yPoints[], points)
• Draws a polygon, with x and y points specified in arrays. Last
• Draws a solid polygon.
argument specifies number of points. • fillPolygon(myPolygon)
• Closed polygon, even if last point different from first.
• Draws specified solid polygon.
• drawPolyline(xPoints[], yPoints[], points)
• Polygon(xValues[], yValues[], numberOfPoints)
• As above but draws a polyline.
• Open polyline. • Constructs a new polygon object.
• myPolygon.addPoint(x, y)
• Add pairs of x-y coordinates to polygon object.
33 34
Cont… Cont…
Example-8: Drawing Polygons and Polylines Outline: Outline:
Polygon poly2 = new Polygon();
import java.awt.*; poly2.addPoint( 165, 135 );
Import poly2.addPoint( 175, 150 );
define paint()
import java.awt.event.*;
import javax.swing.*; poly2.addPoint( 270, 200 );
poly2.addPoint( 200, 220 );
public class DrawPolygons extends JFrame { Class definition poly2.addPoint( 130, 180 );
public DrawPolygons() {
super( "Drawing Polygons" ); g.fillPolygon( poly2 );
setSize( 275, 230 ); }
setVisible(true); // show();
} public static void main( String args[] ) { main() method
DrawPolygons app = new DrawPolygons();
public void paint( Graphics g ) { }
int xValues[ ] = { 20, 40, 50, 30, 20, 15 }; define paint() }
int yValues[ ] = { 50, 50, 60, 80, 80, 60 };
Polygon poly1 = new Polygon( xValues, yValues, 6 ); Program Output
g.drawPolygon( poly1 );
int xValues2[ ] = { 70, 90, 100, 80, 70, 65, 60 };
int yValues2[ ] = { 100, 100, 110, 110, 130, 110, 90 };
g.drawPolyline( xValues2, yValues2, 7 );
int xValues3[ ] = { 120, 140, 150, 190 };
int yValues3[ ] = { 40, 70, 80, 60 };
g.fillPolygon( xValues3, yValues3, 4 );
35 36

You might also like