1 / 70

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

clare
Télécharger la présentation

Draw Shapes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 Paint Window system Component AWT Dispatcher repaint update Multi-threaded! Damage caused

  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 x (w,h) 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,arcWidth,arcHeight); • Filled Rounded Rectangle • g.fillRoundRect(topLeftX,topLeftY,width,height,arcWidth,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 Graphics • Inherits basic drawing ability from Graphics • Adds more advanced drawing ability 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, transformPerform 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.

More Related