26drawing shapes

Download Report

Transcript 26drawing shapes

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
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.
Built-in Graphics Functions

The Java Graphics Objects includes
dozens of drawing functions:
 drawLine()
 drawOval()
 drawPolygon()
 drawRect()
 draw3DRect()
 fillOval()
 fillRect()
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);

Who calls Paint?

public void paint(Graphics g) {...
 Not
the programmer
 Not the JVM
 AWT Event Dispatcher (it runs in a thread).
 called in response to a repaint invocation!
 repaint()
 repaint(1000); // paint invoked in 1 second
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)

Damage control manager
Window system
Component
AWT Dispatcher
repaint
update
Damage caused
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;

Coordinates

Integers
0,0
x
(w,h)
y
Custom painting (1)
Occurs between background and border
 Extend component and customise

 JPanel

e.g. class myPaintingPanel extends JPanel {
 can


recommended
also use atomic components
e.g. class myPaintingButton extends JButton {
Code goes in overridden
paintComponent() method
 public
void paintComponent(Graphics g) {
Custom painting (2)

When writing custom painting code
 should
not reproduce painting functionality of
any other Swing component

Before doing anything else in
paintComponent()
 invoke
super.paintComponent() or
 setOpaque(false)
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)} ]
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;
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
 only repaints a specified area


height);
Component painted after all pending events
dispatched.
Painting should be kept short - Done in event
thread - slows GUI
Formula for a circle

Implicit formula
 (X-xc)^2

+ (Y-yc)^2 = R^2
Parametric Formula
X
= sin(t)+xc
 Y = cos(t)+yc
 T is in the range from 0 to 1 inclusive
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

Vector Graphics
Legend

Stock price, sample rate (once every 30
sec).
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)
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!)
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
Drawing Arcs

Arcs
 Outlined Arc

g.drawArc(topLeftX, topLeftY, width, height,
startAngle, arcAngle);
 Filled Arc

g.fillArc((topLeftX, topLeftY, width, height,
startAngle, arcAngle);
Drawing Rectangles

Rectangle
 Outlined

g.drawRect(topLeftX, topLeftY, width, height);
 Filled

Rectangle
Rectangle
g.fillRect(topLeftX,topLeftY,width,height);
Outlined Rounded Rectangle

g.drawRoundRect(topLeftX,topLeftY,width,height,a
rcWidth,arcHeight);
 Filled

Rounded Rectangle
g.fillRoundRect(topLeftX,topLeftY,width,height,arc
Width,arcHeight);
Drawing on a Blank Picture

You can make pictures from the “blank”
files
 They
will have all white pixels
 640x480.jpg
 7inX95in.jpg
create a “blank” picture with a width
and height

They will also have all white pixels
 Picture
blankPicture = new
Picture(width,height);
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
Bitmapped Versus Vector
Graphics

Some applications use vector graphics
which are programs that produce the
picture
 Used
in Postscript, Flash, and AutoCAD
 Advantages: smaller, easy to change, can be
scaled
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
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);
}}
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
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
Java 2D Demo

http://www.codesounding.org/java2demo.jnlp
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));
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);
Graphics2D inherits from
Graphics
Graphics


Inherits basic drawing ability
from Graphics
Adds more advanced
drawing ability
Graphics2D
Drawing Lines Exercise

Create a new method
(drawWideX) for adding two
wide crossed lines to a picture
 passed
color
 passed line width
Set up the stroke to make the lines
thicker
 g2.setStroke(new
 Draw

BasicStroke(width));
the lines
You can use redMotorcycle.jpg to test.
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)
Colors and paints..



java.awt.GradientPaint
(smooth transition between 2 colors)


public Color brighter(), darker()
public static Color black, blue, cyan,
darkGray, gray, green, lightGray, magenta,
orange, pink, red, white, yellow
public GradientPaint(float x1, float y1, Color
color1, float x2, float y2, Color color2)
java.awt.TexturePaint
(use an image as a "paint" background)
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)
Polygons






public void drawPolygon(int[] xpoints,
ypoints, int len)
public void fillPolygon(int[] xpoints,
ypoints, int len)
public void drawRect(int x, int y, int
public void fillRect(int x, int y, int
public void drawArc(...)
public void fillArc(...)
...
int[]
int[]
w, int h)
w, int h)
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
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,
transform
Perform various coordinate transformations on
the Graphics2D context.
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.
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.
Shapes

Rectangle2D.Double(double x, double y,
double w, double h)
A rectangle, which is a generalization of a square.
RoundRectangle2D

RoundRectangle2D.Double(
double x, double y, double w,
double h, double arcx, double
arcy)
A rounded rectangle.

GeneralPath()
A customizable polygon.
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.
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.
Strokes (pen styles)
Graphics2D
 public
void setStroke(Stroke s)
Sets type of drawing pen (color, width, style)
that will be used by this Graphics2D.
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
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));
}
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));
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);
}}
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);
}
Using Graphics2D to Copy an
Image
public 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);
}
Testing the Copy Method
Picture p1 = new
Picture(FileChooser.getMediaPath("beach.
jpg"));
 Picture p2 = new
Picture(FileChooser.getMediaPath("turtle.j
pg"));
 p1.copy2D(p2,194,304);
 p1.show();

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).
Classes for imaging

java.awt.Toolkit
Gets images from disk or internet



public static Toolkit getDefaultToolkit()
public Image getImage(String filename)
public Image getImage(URL address)
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.Image
Represents a graphic image (BMP, GIF, ...)



public int getWidth(ImageObserver obs)
public int getHeight(ImageObserver obs)
java.awt.image.BufferedImage
A blank graphic image surface onto which you can draw
public BufferedImage(int w, int h, int type)
 public Graphics getGraphics()

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) {}
A helper method to load and
return one image
public Image
loadImage(String filename)
Advanced: anti-aliasing

Onscreen text and shapes can have
jagged edges, or aliases. These can be
removed by smoothing, or anti-aliasing,
the panel.
Graphics2D

public void setRenderingHint(
RenderingHints.Key key,
Object value)
 Example:
g2.setRenderingHint(RenderingHints
.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
;
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)
JToolBar
A movable container to hold
common buttons, commands, etc
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.
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)!
Summary

Graphics class for simple 2d drawing
 Lines,
rectangles, ovals, polygons, strings,
images

Graphics2D for more advanced drawing
 Width

of paint brush, paint geometric objects
Graphics2D inherts from Graphics
 Means
it can do the same methods
 But also adds others