Download Introduction to 2D Graphics & Java 2D and more Study notes Java Programming in PDF only on Docsity!
Week 4 – Part 2
Introduction to 2D Graphics & Java 2D
Vector graphics
! Use of geometric primitives: points, lines, curves, etc.
! Primitives are created by using mathematical
equations
! Can be zoomed infinitively, moved or transformed
without losing in quality
Raster (bitmap) graphics
! Images represented as pixels
! Resolution dependent: scaling affects image quality
! Stored in image files
2D graphics
Java 2D API
Provides 2D graphics, text & image capabilities
! Wide range of geometric primitives
! Mechanisms for hit detection of shapes, text, images
! Color & transparency
! Transformations
! Printing
! Control of the quality of rendering
Java 2D – Base classes
Graphics class : abstract base class for all graphics
contexts, allowing applications to draw onto components
public class RectWidget extends JPanel { private int posx, posy, w, h; private Color color; public RectWidget(int x, int y, int w, int h, Color color){ this.posx = x; this.posy = y; this.w = w; this.h = h; this.color = color; } public void paint( Graphics g ) { g.setColor(color); g.drawRect(x, y, w, h); } }
Java 2D – Base classes
Graphics2D class : extends Graphics class to provide more
sophisticated control over geometry, transformations, etc.
private double x, y, w, h; ... public void paint( Graphics g ) { Graphics2D g2 = (Graphics2D)g; g2.draw(new Rectangle2D.Double(x , y, w, h)); }
Geometric primitives
Bézier curves
Parametric curves widely used in Computer Graphics
Used to model smooth curves that can be scaled indefinetely
First studied by mathematician Paul de Casteljau (1959) and
widely publicized by Pierre Bézier (1962)
Bézier curves
Defined by a set of control points: P
0, ...,
P
n
Linear Bézier curve : straight line between P 0 and P 1
B(t) = (1 – t )P 0 + t P 1 , t ∈ [0,1] Quadratic Bézier curve : B(t) = (1 - t ) 2 P 0 +2(1 - t ) t P 1 + t 2 P 2 , t ∈ [0,1] Cubic Bézier curve : B(t) = (1 – t )^3 P 0 +3(1 – t )^2 t P 1 +3(1- t ) t^2 P 2 + t^3 P 3 , t ∈ [0,1]
Curves from points
Given a sequence of points, how do we create a
smooth curve?
Curves from points
Given a sequence of points, how do we create a
smooth curve?
Easy but ugly: connect the points with straight lines
Arbitrary shapes
GeneralPath path = new GeneralPath();
Move the current point of the path to the given point path.moveTo(x, y); Add a line segment to the current path path.lineTo(x, y); Add a quadratic curve segment to the current path path.quadTo(ctrlx, ctrly, x2, y2); Add a cubic curve segment to the current pathclosePath path.curveTo(ctrlx1, ctrly1, ctrlx2, ctrly2, x3, y3); Close the current path path.closePath();
Stroking and painting
stroke patterns
filling patterns
gradient filling colors
Restricts the drawing area to be rendered
Clipping
Restricts the drawing area to be rendered
rect.setRect(x + marginx, y + marginy, w, h); g2.clip(rect); g2.drawImage(image, x, y, null);
Clipping