Draw Shapes

70
Draw Shapes Introduction to simple graphics

description

Draw Shapes. Introduction to simple graphics. What is a graphics context?. An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics You can get instances of the Graphics class From the paint method From an instance of an java.awt.Image From a java.awt.Component. - PowerPoint PPT Presentation

Transcript of Draw Shapes

Page 1: Draw Shapes

Draw Shapes

Introduction to simple graphics

Page 2: Draw Shapes

What is a graphics context?

An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics You can get instances of the Graphics class

From the paint methodFrom an instance of an java.awt.ImageFrom a java.awt.Component

Page 3: Draw Shapes

Why do I need a graphics context? To get access to simple 2D draw methods.

- Draw Business graphics

- Draw Vectors into the screen.

- Draw text

- Draw java.awt.Images

- simple shapes (2D)

- I can print vectors, and bit map.

Page 4: Draw Shapes

Built-in Graphics Functions

The Java Graphics Objects includes dozens of drawing functions:drawLine()drawOval()drawPolygon()drawRect()draw3DRect() fillOval() fillRect()

Page 5: Draw Shapes

Drawing

Draw a yellow-filled rectangle:g.setColor (new Color (255,255,206));g.fillRect (50, 50, 215,100);

Draw a black perimeter around the yellow rectangle.g.setColor (Color.black);g.drawRect (50,50,215,100);

Draw a line underneath the welcome message.g.drawLine (80,105,227,105);

Page 6: Draw Shapes

Who calls Paint?

public void paint(Graphics g) {...Not the programmerNot the JVMAWT Event Dispatcher (it runs in a thread).called in response to a repaint invocation!repaint()repaint(1000); // paint invoked in 1 second

Page 7: Draw Shapes

When does the Damage control manager invokes repaint? If there is damage, damage control for the

window causes repaint. Window resize Window exposed Component demands. repaint(int x, int y, int w, int h)

Page 8: Draw Shapes

Damage control manager

AWT Dispatcher

Component

repaint

Damage caused

update

Window system

Page 9: Draw Shapes

Dimensions

Windows have dimension let Window w = new Window(); //then Dimension d = w.getSize(); Components have dimensions too. Int w = d.width; Int h = d.height;

Page 10: Draw Shapes

Coordinates

Integers

0,0

(w,h)

x

y

Page 11: Draw Shapes

Custom painting (1)

Occurs between background and border Extend component and customise

JPanel recommended e.g. class myPaintingPanel extends JPanel {

can also use atomic components e.g. class myPaintingButton extends JButton {

Code goes in overridden paintComponent() methodpublic void paintComponent(Graphics g) {

Page 12: Draw Shapes

Custom painting (2)

When writing custom painting codeshould not reproduce painting functionality of

any other Swing component

Before doing anything else in paintComponent() invoke super.paintComponent() orsetOpaque(false)

Page 13: Draw Shapes

Painting coordinates

Component sizes in pixels(0,0) at top left corner(width-1,height-1) at bottom right corner

Border sizes (e.g. a 1-pixel border)(1,1) at top left(width-2, height-2) at bottom right

General painting area for b pixel border [ {b,b} : {w-(b+1), h-(b+1)} ]

Page 14: Draw Shapes

Getting painting coordinates

Use component getWidth() and getHeight() Get border sizes with getInsets()

e.g. to get width and height of custom painting area use something like:

Insets insets = getInsets();int currentWidth = getWidth() -

insets.left - insets.right;int currentHeight = getHeight() -

insets.top - insets.bottom;

Page 15: Draw Shapes

Repainting custom paints

Calling repaint() method requests a repaint to occur repaint()

paints whole component & any others that need it if transparent repaint(int leftx,int lefty,int width,int height);

only repaints a specified area

Component painted after all pending events dispatched.

Painting should be kept short - Done in event thread - slows GUI

Page 16: Draw Shapes

Formula for a circle

Implicit formula(X-xc)^2 + (Y-yc)^2 = R^2

Parametric Formula X = sin(t)+xcY = cos(t)+ycT is in the range from 0 to 1 inclusive

Page 17: Draw Shapes

For a line

Y=mx+b, where m = slope, b = y intercept F(t) = P0(1-t)+P1(t) P0 = (x0,y0) P1=(x1,y1) F(t)=P0-p0t+p1t=t(p1-p0)+p0

Page 18: Draw Shapes

Vector Graphics

Page 19: Draw Shapes

Legend

Stock price, sample rate (once every 30 sec).

Page 20: Draw Shapes

Drawing text strings

Graphics2D public void drawString(String s, int x, int y)Draws given string with its first letter's bottom-left corner at the given location. The string is drawn using the Graphics2D's current color and

font settings. Before drawing the string, you can set the font, color, and other

attributes.(see next slides)

Page 21: Draw Shapes

Fonts

Graphics2D public void setFont(Font f)

Sets this Graphics context to start writing text in the given font. (Forgotten at end of paintComponent call!)

Page 22: Draw Shapes

java.awt.Font

Text styles used when drawing Strings on the panel

public Font(String name, int style, int size) some predefined font names:

"Serif", "SansSerif", "Monospaced" font styles (can be combined with + operator):

Font.BOLD Font.ITALIC Font.PLAIN

Page 23: Draw Shapes

Drawing Arcs

ArcsOutlined Arc

g.drawArc(topLeftX, topLeftY, width, height, startAngle, arcAngle);

Filled Arc g.fillArc((topLeftX, topLeftY, width, height,

startAngle, arcAngle);

Page 24: Draw Shapes

Drawing Rectangles

RectangleOutlined Rectangle

g.drawRect(topLeftX, topLeftY, width, height);

Filled Rectangle g.fillRect(topLeftX,topLeftY,width,height);

Page 25: Draw Shapes

Outlined Rounded Rectangle

g.drawRoundRect(topLeftX,topLeftY,width,height,arcWidth,arcHeight);

Filled Rounded Rectangle g.fillRoundRect(topLeftX,topLeftY,width,height,arc

Width,arcHeight);

Page 26: Draw Shapes

Drawing on a Blank Picture

You can make pictures from the “blank” filesThey will have all white pixels640x480.jpg7inX95in.jpg

Page 27: Draw Shapes

create a “blank” picture with a width and height

They will also have all white pixelsPicture blankPicture = new

Picture(width,height);

Page 28: Draw Shapes

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 arc

Page 29: Draw Shapes

Bitmapped Versus Vector Graphics Some applications use vector graphics

which are programs that produce the pictureUsed in Postscript, Flash, and AutoCADAdvantages: smaller, easy to change, can be

scaled

Page 30: Draw Shapes

Precision Drawings

draw a stack of filled rectangles starting from the lightest one at the bottom right and the darkest one at the top left. 10 pixels between each Not easy with drawing

packages

Page 31: Draw Shapes

Draw Filled Rectangles Method

public void drawFilledRectangles(){ Graphics g = this.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); }}

Page 32: Draw Shapes

Java 2D Graphics – java.awt 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

Page 33: Draw Shapes

Advanced Drawing

Support for different types of brushes Line thickness, dashed lines, etc

Supports cubic curves and general pathsDrawing of gradients and texturesMove, rotate, scale and shear text and

graphicsCreate composite images

Page 34: Draw Shapes

Java 2D Demo

http://www.codesounding.org/java2demo.jnlp

Page 35: Draw Shapes

How To Use Java 2D

Cast the Graphics class to Graphics2D Graphics2D g2 = (Graphics2D) gObj;

Set up the stroke if desired (type of pen) g2.setStroke(new BasicStroke(widthAsFloat));

Page 36: Draw Shapes

Set up any Color, GradientPaint, or TexturePaint

g2.setPaint(Color.blue); g2.setPaint(blueToPurpleGradient); g2.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

g2.draw(line2d); Fill a geometric shape

g2.fill(rectangle2d);

Page 37: Draw Shapes

Graphics2D inherits from Graphics Inherits basic drawing ability

from Graphics Adds more advanced

drawing ability

Graphics

Graphics2D

Page 38: Draw Shapes

Drawing Lines Exercise

Create a new method (drawWideX) for adding two wide crossed lines to a picture passed color passed line width

Page 39: Draw Shapes

Set up the stroke to make the lines thicker

g2.setStroke(new BasicStroke(width));Draw the lines

You can use redMotorcycle.jpg to test.

Page 40: Draw Shapes

Colors and paints

java.awt.Color(a simple single-colored paint) public Color(int r, int g, int b) public Color(int r, int g, int b, int alpha)

a partially-transparent color (range 0-255, 0=transparent)

Page 41: Draw Shapes

Colors and paints..

public Color brighter(), darker() public static Color black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow

java.awt.GradientPaint(smooth transition between 2 colors) public GradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2)

java.awt.TexturePaint(use an image as a "paint" background)

Page 42: Draw Shapes

Shapes (old style)

Graphics2D public void drawLine(int x1, int y1, int x2, int y2)

public void drawOval(int x, int y, int w, int h)

public void fillOval(int x, int y, int w, int h)

Page 43: Draw Shapes

Polygons

public void drawPolygon(int[] xpoints, int[] ypoints, int len)

public void fillPolygon(int[] xpoints, int[] ypoints, int len)

public void drawRect(int x, int y, int w, int h) public void fillRect(int x, int y, int w, int h) public void drawArc(...) public void fillArc(...)

...

Drawing methods for drawing various lines and shapes on a Graphics context. Not recommended to be used replaced by draw(Shape), fill(Shape) in Graphics2D

Page 44: Draw Shapes

Graphics2D shape methods

public void draw(Shape s)Draws the outline of the given shape using this Graphics2D's current pen.

public void fill(Shape s)Draws outline and fills inside of given shape.

rotate, scale, translate, shear, transformPerform various coordinate transformations on the Graphics2D context.

Page 45: Draw Shapes

Shapes (in package java.awt.geom)

Arc2D.Double(double x, double y, double w,

double h, double start, double extent, int type)An arc, which is a portion of an ellipse.

Page 46: Draw Shapes

Ellipse2D

Ellipse2D.Double(double x, double y, double w, double h)An ellipse, which is a generalization of a circle.

Line2D.Double(double x1, double y1, double x2, double y2)Line2D.Double(Point p1, Point p2)A line between two points.

Page 47: Draw Shapes

Shapes

Rectangle2D.Double(double x, double y, double w, double h)A rectangle, which is a generalization of a square.

Page 48: Draw Shapes

RoundRectangle2D

RoundRectangle2D.Double( double x, double y, double w, double h, double arcx, double arcy)A rounded rectangle.

GeneralPath()A customizable polygon.

Page 49: Draw Shapes

Methods of to all shapes

public boolean contains(double x, double y)public boolean contains(Point2D p)Whether the given point is contained inside the bounds of this

shape.

Page 50: Draw Shapes

Rectangle

public Rectangle getBounds()A rectangle representing the bounding box around this shape.

public double getCenterX() / getCenterY() public double getMinX() / getMinY() public double getMaxX() / getMaxY()

Various corner or center coordinates within the shape.

public boolean intersects(double x, double y, double w, double h)

public boolean intersects(Rectangle2D r)Whether this shape touches the given rectangular region.

Page 51: Draw Shapes

Strokes (pen styles)

Graphics2D public void setStroke(Stroke s)

Sets type of drawing pen (color, width, style)that will be used by this Graphics2D.

Page 52: Draw Shapes

java.awt.BasicStroke

A pen stroke for drawing outlines

public BasicStroke(float width) public BasicStroke(float width, int cap, int join)

public BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)

cap: CAP_BUTT, CAP_ROUND, CAP_SQUARE join: JOIN_BEVEL, JOIN_MITER, JOIN_ROUND

Page 53: Draw Shapes

Drawing example 1

public void paintComponent(Graphics g) {

super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.fill(new Rectangle2D.Double(10, 30, 60, 35));

g2.fill(new Ellipse2D.Double(80, 40, 50, 70));

}

Page 54: Draw Shapes

Drawing example 2

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g;

g2.setPaint(Color.BLACK); g2.fill(new Rectangle2D.Double(10, 30, 100, 50)); g2.setPaint(Color.RED); g2.fill(new Ellipse2D.Double(20, 70, 20, 20)); g2.fill(new Ellipse2D.Double(80, 70, 20, 20)); g2.setPaint(Color.CYAN); g2.fill(new Rectangle2D.Double(80, 40, 30, 20));}

Page 55: Draw Shapes

Drawing example 3

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g;g2.setPaint(Color.BLUE);for (int i = 1; i <= 10; i++) {g2.fill(new Ellipse2D.Double(15 * i, 15 * i, 30, 30));

} g2.setPaint(Color.MAGENTA); for (int i = 1; i <= 10; i++) { g2.fill(new Ellipse2D.Double(15 * (11 - i), 15 * i,

30, 30); }}

Page 56: Draw Shapes

Using a Graphics Object to Copy an Image

public void copy(Picture source, int x, int y){

// get the graphics object

Graphics g = this.getGraphics();

// copy the image

g.drawImage(source.getImage(),x,y,null);

}

Page 57: Draw Shapes

Using Graphics2D to Copy an Imagepublic void copy2D(Picture source, int x, int

y){ // get the graphics object

Graphics g = this.getGraphics();

Graphics g2 = (Graphics2D) g;

// copy the image

g2.drawImage(source.getImage(),x,y,null);

}

Page 58: Draw Shapes

Testing the Copy Method

Picture p1 = new Picture(FileChooser.getMediaPath("beach.jpg"));

Picture p2 = new Picture(FileChooser.getMediaPath("turtle.jpg"));

p1.copy2D(p2,194,304); p1.show();

Page 59: Draw Shapes

Drawing images

Graphics2D public void drawImage(Image i, int x, int y, ImageObserver io)

public void drawImage(Image i, int x, int y, int width, int height, ImageObserver io)

Draws given image object on this Graphics context with its top-left corner at given location (pass the panel as the ImageObserver).

Page 60: Draw Shapes

Classes for imaging

java.awt.ToolkitGets images from disk or internet public static Toolkit getDefaultToolkit() public Image getImage(String filename) public Image getImage(URL address)

Page 61: Draw Shapes

java.awt.MediaTracker

Ensures that images are loaded fully public MediaTracker(Component comp) public void addImage(Image img, int id) public void waitForAll()

throws InterruptedException

java.awt.ImageRepresents a graphic image (BMP, GIF, ...) public int getWidth(ImageObserver obs) public int getHeight(ImageObserver obs)

java.awt.image.BufferedImageA blank graphic image surface onto which you can draw public BufferedImage(int w, int h, int type) public Graphics getGraphics()

Page 62: Draw Shapes

Images, continued

Code to load an image:Toolkit tk = Toolkit.getDefaultToolkit();

Image img = tk.getImage("myimage.jpg");

MediaTracker mt = new MediaTracker(this);

mt.addImage(img, 0); // any ID will do

try {

mt.waitForAll();

} catch (InterruptedException ie) {}

Page 63: Draw Shapes

A helper method to load and return one image

public Image loadImage(String filename)

Page 64: Draw Shapes

Advanced: anti-aliasing

Onscreen text and shapes can have jagged edges, or aliases. These can be removed by smoothing, or anti-aliasing, the panel.

Page 65: Draw Shapes

Graphics2D

public void setRenderingHint( RenderingHints.Key key, Object value)Example:g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

Page 66: Draw Shapes

Icon/ImageIcon

Allows you to put a picture on a button, label or other component

public class ImageIcon implements Icon public ImageIcon(String filename) public ImageIcon(URL address)

in JButton, JRadioButton, JCheckBox, JLabel, etc... constructor that takes an Icon public void setIcon(Icon) public void setSelectedIcon(Icon) public void setRolloverIcon(Icon)

Page 67: Draw Shapes

JToolBar

A movable container to hold common buttons, commands, etc

Page 68: Draw Shapes

JToolBar

public JToolBar() public JToolBar(int orientation) public JToolBar(String title) public JToolBar(String title, int orientation)

Constructs a new tool bar, optionally with a title and orientation; can be JToolBar.HORIZONTAL or VERTICAL, defaults to horizontal

public void add(Component comp)Adds the given component to this tool bar's horizontal/vertical flowing layout.

Page 69: Draw Shapes

JToolBar: Usage

construct toolbar add items (usually buttons) to toolbar add toolbar to edge of BorderLayout of

content pane (usually NORTH)don't put anything in other edges (N/S/E/W)!

Page 70: Draw Shapes

Summary Graphics class for simple 2d drawing

Lines, rectangles, ovals, polygons, strings, images

Graphics2D for more advanced drawingWidth of paint brush, paint geometric objects

Graphics2D inherts from GraphicsMeans it can do the same methodsBut also adds others