Presentation is loading. Please wait.

Presentation is loading. Please wait.

Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics.

Similar presentations


Presentation on theme: "Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics."— Presentation transcript:

1 Draw Shapes Introduction to simple graphics

2 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

3 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.

4 Built-in Graphics Functions The Java Graphics Objects includes dozens of drawing functions:  drawLine()  drawOval()  drawPolygon()  drawRect()  draw3DRect()  fillOval()  fillRect()

5 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);

6 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

7 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)

8 Damage control manager AWT Dispatcher Component repaint Damage caused update Window system

9 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;

10 Coordinates Integers 0,0 (w,h) x y

11 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() method  public void paintComponent(Graphics g) {

12 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)

13 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)} ]

14 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;

15 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

16 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

17 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

18 Vector Graphics

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

20 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)

21 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!)

22 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

23 Drawing Arcs Arcs  Outlined Arc g.drawArc(topLeftX, topLeftY, width, height, startAngle, arcAngle);  Filled Arc g.fillArc((topLeftX, topLeftY, width, height, startAngle, arcAngle);

24 Drawing Rectangles Rectangle  Outlined Rectangle g.drawRect(topLeftX, topLeftY, width, height);  Filled Rectangle g.fillRect(topLeftX,topLeftY,width,height);

25 Outlined Rounded Rectangle g.drawRoundRect(topLeftX,topLeftY,width,height,a rcWidth,arcHeight);  Filled Rounded Rectangle g.fillRoundRect(topLeftX,topLeftY,width,height,arc Width,arcHeight);

26 Drawing on a Blank Picture You can make pictures from the “blank” files  They will have all white pixels  640x480.jpg  7inX95in.jpg

27 create a “blank” picture with a width and height They will also have all white pixels  Picture blankPicture = new Picture(width,height);

28 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

29 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

30 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

31 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); }}

32 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

33 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

34 Java 2D Demo http://www.codesounding.org/java2demo.jnlp

35 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));

36 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);

37 Graphics2D inherits from Graphics Inherits basic drawing ability from Graphics Adds more advanced drawing ability Graphics Graphics2D

38 Drawing Lines Exercise Create a new method (drawWideX) for adding two wide crossed lines to a picture  passed color  passed line width

39 Set up the stroke to make the lines thicker  g2.setStroke(new BasicStroke(width));  Draw the lines You can use redMotorcycle.jpg to test.

40 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)

41 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)

42 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)

43 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

44 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.

45 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.

46 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.

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

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

49 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.

50 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.

51 Strokes (pen styles) Graphics2D  public void setStroke(Stroke s) Sets type of drawing pen (color, width, style) that will be used by this Graphics2D.

52 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

53 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)); }

54 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)); }

55 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); }}

56 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); }

57 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); }

58 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();

59 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 ).

60 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)

61 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()

62 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) {}

63 A helper method to load and return one image public Image loadImage(String filename)

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

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

66 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)

67 JToolBar A movable container to hold common buttons, commands, etc

68 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.

69 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)!

70 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


Download ppt "Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics."

Similar presentations


Ads by Google