-
Notifications
You must be signed in to change notification settings - Fork 0
/
PennDraw.java
1544 lines (1338 loc) · 61 KB
/
PennDraw.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************
* Compilation: javac PennDraw.java
* Execution: java PennDraw
*
* Standard drawing library. This class provides a basic capability for
* creating drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.
*
* Todo
* ----
* - Add support for gradient fill, stipple, etc.
* - On some systems, drawing a line (or other shape) that extends way
* beyond canvas (e.g., to infinity) dimensions does not get drawn.
*
* Remarks
* -------
* - don't use AffineTransform for rescaling since it
* messes up images, strings, and penRadius
* - careful using setFont in inner loop within an animation -
* it can cause flicker
*
*************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import java.util.TreeSet;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* <i>Standard draw</i>. This class provides a basic capability for
* creating drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
* @author Benedict Brown
*/
public final class PennDraw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
// version number
public static final long VERSION = 2016011311; // YEAR MONTH DAY HOUR (to allow >= comparison)
// pre-defined colors
public static final Color BLACK = Color.BLACK;
public static final Color BLUE = Color.BLUE;
public static final Color CYAN = Color.CYAN;
public static final Color DARK_GRAY = Color.DARK_GRAY;
public static final Color GRAY = Color.GRAY;
public static final Color GREEN = Color.GREEN;
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
public static final Color MAGENTA = Color.MAGENTA;
public static final Color ORANGE = Color.ORANGE;
public static final Color PINK = Color.PINK;
public static final Color RED = Color.RED;
public static final Color WHITE = Color.WHITE;
public static final Color YELLOW = Color.YELLOW;
/**
* Shade of blue used in Introduction to Programming in Java.
* It is Pantone 300U. The RGB values are approximately (9, 90, 166).
*/
public static final Color BOOK_BLUE = new Color( 9, 90, 166);
public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);
/**
* Shade of red used in Algorithms 4th edition.
* It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
*/
public static final Color BOOK_RED = new Color(150, 35, 31);
// default colors
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// current pen color
private static Color penColor;
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 512;
private static int width = DEFAULT_SIZE;
private static int height = DEFAULT_SIZE;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// current pen radius
private static double penRadius;
// show we draw immediately or wait until next show?
private static boolean defer = false;
// time in milliseconds (from currentTimeMillis()) when we can draw again
// used to control the frame rate
private static long nextDraw = -1;
// frame rate for animation mode in ms (60000 / fps)
// 0 to draw as soon as advance() is called
// -1 to disable animation mode
private static int animationSpeed = -1;
// boundary of drawing canvas, 0% border, scale factor to convert back to window coordinates
// (used to be a 5% border, and we might as well leave the constant in the code so
// it's easy to add a border back in if necessary)
private static final double BORDER = 0;
private static final double DEFAULT_XMIN = 0.0;
private static final double DEFAULT_XMAX = 1.0;
private static final double DEFAULT_YMIN = 0.0;
private static final double DEFAULT_YMAX = 1.0;
private static double xmin, ymin, xmax, ymax;
private static double xscale, yscale;
// for synchronization
private static Object mouseLock = new Object();
private static Object keyLock = new Object();
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16);
// current font
private static Font font;
// double buffered graphics
private static BufferedImage offscreenImage, onscreenImage;
private static Graphics2D offscreen, onscreen;
// singleton for callbacks: avoids generation of extra .class files
private static PennDraw std = new PennDraw();
// the frame for drawing to the screen
private static JFrame frame;
// mouse state
private static boolean mousePressed = false;
private static double mouseX = 0;
private static double mouseY = 0;
// queue of typed key characters
private static LinkedList<Character> keysTyped = new LinkedList<Character>();
// set of key codes currently pressed down
private static TreeSet<Integer> keysDown = new TreeSet<Integer>();
// singleton pattern: client can't instantiate
private PennDraw() { }
// static initializer
static { init(); }
/**
* Set the window size to the default size 512-by-512 pixels.
* This method must be called before any other commands.
*/
public static void setCanvasSize() {
setCanvasSize(DEFAULT_SIZE, DEFAULT_SIZE);
}
/**
* Set the window size to w-by-h pixels.
* This method resets the x- and y-scales, fonts, colors, pen radius, etc., and clears the screen
*
* @param w the width as a number of pixels
* @param h the height as a number of pixels
* @throws a IllegalArgumentException if the width or height is 0 or negative
*/
public static void setCanvasSize(int w, int h) {
if (w < 1 || h < 1) throw new IllegalArgumentException("width and height must be positive");
width = w;
height = h;
init();
}
// init
private static void init() {
// init() should only be called once at class initialization, and when the canvas is resized
if (frame != null) frame.setVisible(false);
frame = new JFrame();
offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
onscreen = onscreenImage.createGraphics();
setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
// add antialiasing
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
// frame stuff
ImageIcon icon = new ImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(std);
draw.addMouseMotionListener(std);
frame.setContentPane(draw);
frame.addKeyListener(std); // JLabel cannot get keyboard focus
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes all windows
// frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // closes only current window
frame.setTitle("Standard Draw");
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
}
// create the menu bar (changed to private)
private static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Save... ");
menuItem1.addActionListener(std);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
return menuBar;
}
/*************************************************************************
* User and screen coordinate systems
*************************************************************************/
/**
* Set the x-scale to be the default (between 0.0 and 1.0).
*/
public static void setXscale() { setXscale(DEFAULT_XMIN, DEFAULT_XMAX); }
/**
* Set the y-scale to be the default (between 0.0 and 1.0).
*/
public static void setYscale() { setYscale(DEFAULT_YMIN, DEFAULT_YMAX); }
/**
* Set the x-scale (a 10% border is added to the values)
* @param min the minimum value of the x-scale
* @param max the maximum value of the x-scale
*/
public static void setXscale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
xmin = min - BORDER * size;
xmax = max + BORDER * size;
setTransform();
}
}
/**
* Set the y-scale (a 10% border is added to the values).
* @param min the minimum value of the y-scale
* @param max the maximum value of the y-scale
*/
public static void setYscale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
ymin = min - BORDER * size;
ymax = max + BORDER * size;
setTransform();
}
}
/**
* Set the x-scale and y-scale (a 10% border is added to the values)
* @param min the minimum value of the x- and y-scales
* @param max the maximum value of the x- and y-scales
*/
public static void setScale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
xmin = min - BORDER * size;
xmax = max + BORDER * size;
ymin = min - BORDER * size;
ymax = max + BORDER * size;
setTransform();
}
}
// helper function that sets the canvas transform based on xmin, xmax, etc.
private static void setTransform() {
xscale = width / (xmax - xmin);
yscale = height / (ymax - ymin);
}
// helper functions that scale from user coordinates to screen coordinates and back
private static double scaleX(double x) { return xscale * (x - xmin); }
private static double scaleY(double y) { return yscale * (ymax - y); }
private static double factorX(double w) { return w * width / Math.abs(xmax - xmin); }
private static double factorY(double h) { return h * height / Math.abs(ymax - ymin); }
private static double userX(double x) { return xmin + x / xscale; }
private static double userY(double y) { return ymax - y / yscale; }
/**
* Clear the screen to the default color (white).
*/
public static void clear() { clear(DEFAULT_CLEAR_COLOR); }
/**
* Clear the screen to the given color.
* @param color the Color to make the background
*/
public static void clear(Color color) {
offscreen.setColor(color);
filledRectangle(0.5 * (xmax + xmin), 0.5 * (ymax + ymin),
0.5 * (xmax - xmin), 0.5 * (ymax - ymin));
offscreen.setColor(penColor);
draw();
}
/**
* Clear the screen to the given color.
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range
*/
public static void clear(int red, int green, int blue) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of green must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of blue must be between 0 and 255");
clear(new Color(red, green, blue));
}
/**
* Clear the screen to the given color.
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @param alpha the amount of alpha (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range
*/
public static void clear(int red, int green, int blue, int alpha) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of green must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of blue must be between 0 and 255");
if (alpha < 0 || alpha >= 256) throw new IllegalArgumentException("amount of alpha must be between 0 and 255");
clear(new Color(red, green, blue, alpha));
}
/**
* Get the current pen radius.
*/
public static double getPenRadius() { return penRadius; }
/**
* Set the pen size to the default (.002).
*/
public static void setPenRadius() { setPenRadius(DEFAULT_PEN_RADIUS); }
/**
* Set the radius of the pen to the given size.
* @param r the radius of the pen
* @throws IllegalArgumentException if r is negative
*/
public static void setPenRadius(double r) {
if (r < 0) throw new IllegalArgumentException("pen radius must be nonnegative");
penRadius = r;
float scaledPenRadius = (float) (r * DEFAULT_SIZE);
BasicStroke stroke = new BasicStroke(scaledPenRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
// BasicStroke stroke = new BasicStroke(scaledPenRadius);
offscreen.setStroke(stroke);
}
/**
* Set the width of the pen to the given size based on the window width
* @param w the width of the pen in pixels
* @throws IllegalArgumentException if width is negative
*/
public static void setPenWidthInPixels(double w) {
if (w < 0) throw new IllegalArgumentException("pen radius must be nonnegative");
setPenRadius(w / (2 * width));
}
/**
* Set the width of the pen to the given size based on the window width and screen resolution
* @param w the width of the pen in points (72 points/pinch)
* @throws IllegalArgumentException if width is negative
*/
public static void setPenWidthInPoints(double w) {
if (w < 0) throw new IllegalArgumentException("pen radius must be nonnegative");
int dpi = frame.getToolkit().getScreenResolution();
setPenRadius(dpi * w / (144 * width));
}
/**
* Get the current pen color.
*/
public static Color getPenColor() { return penColor; }
/**
* Set the pen color to the default color (black).
*/
public static void setPenColor() { setPenColor(DEFAULT_PEN_COLOR); }
/**
* Set the pen color to the given color. The available pen colors are
* BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA,
* ORANGE, PINK, RED, WHITE, and YELLOW.
* @param color the Color to make the pen
*/
public static void setPenColor(Color color) {
penColor = color;
offscreen.setColor(penColor);
}
/**
* Set the pen color to the given RGB color.
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range
*/
public static void setPenColor(int red, int green, int blue) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of green must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of blue must be between 0 and 255");
setPenColor(new Color(red, green, blue));
}
/**
* Set the pen color to the given RGBA color.
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @param alpha the amount of alpha (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, blue, or alpha are outside prescribed range
*/
public static void setPenColor(int red, int green, int blue, int alpha) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of green must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of blue must be between 0 and 255");
if (alpha < 0 || alpha >= 256) throw new IllegalArgumentException("amount of alpha must be between 0 and 255");
setPenColor(new Color(red, green, blue, alpha));
}
/**
* Get the current font.
*/
public static Font getFont() { return font; }
/**
* List all available fonts
* Code from http://alvinalexander.com/blog/post/jfc-swing/swing-faq-list-fonts-current-platform
*/
public static void listFonts() {
String fonts[] =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (String s : fonts)
System.out.println(s);
}
/**
* Set the font to the default font (sans serif, 16 point).
*/
public static void setFont() { setFont(DEFAULT_FONT); }
/**
* Set the font to the given value.
* @param f the font to make text
*/
public static void setFont(Font f) {
font = f;
offscreen.setFont(f);
}
/**
* Set the font to the given font, with the same style and point size as the current font.
* @param fontName the font to make text
*/
public static void setFont(String fontName) {
setFont(new Font(fontName, font.getStyle(), font.getSize()));
}
/**
* Set the font to the given font and size, with the same style as the current font.
* @param fontName the font to make text
* @param pointSize the font to make text
*/
public static void setFont(String fontName, double pointSize) {
setFont(fontName);
setFont(font.deriveFont((float) pointSize));
}
/**
* Set the font to the specified point size
* @param pointSize the desired font size
*/
public static void setFontSize(double pointSize) {
setFont(font.deriveFont((float) pointSize));
}
/**
* Set the font to the specified height in pixels. The conversion
* is approximate due to limitations in Java.
* @param pixelHeight the desired font size in pixels
*/
public static void setFontSizeInPixels(double pixelHeight) {
int dpi = frame.getToolkit().getScreenResolution();
double pointSize = pixelHeight * dpi / 72;
System.out.println(dpi);
System.out.println(pointSize);
setFont(font.deriveFont((float) pointSize));
}
/**
* Set the font to a plain style (no bold or italic)
*/
public static void setFontPlain() {
setFont(font.deriveFont(Font.PLAIN));
}
/**
* Set the font to a bold style (no italic)
*/
public static void setFontBold() {
setFont(font.deriveFont(Font.BOLD));
}
/**
* Set the font to an italics style (no bold)
*/
public static void setFontItalic() {
setFont(font.deriveFont(Font.ITALIC));
}
/**
* Set the font to a bold italic style
*/
public static void setFontBoldItalic() {
setFont(font.deriveFont(Font.BOLD | Font.ITALIC));
}
/*************************************************************************
* Drawing geometric shapes.
*************************************************************************/
/**
* Draw a line from (x0, y0) to (x1, y1).
* @param x0 the x-coordinate of the starting point
* @param y0 the y-coordinate of the starting point
* @param x1 the x-coordinate of the destination point
* @param y1 the y-coordinate of the destination point
*/
public static void line(double x0, double y0, double x1, double y1) {
offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));
draw();
}
/**
* Draw one pixel at (x, y).
* @param x the x-coordinate of the pixel
* @param y the y-coordinate of the pixel
*/
private static void pixel(double x, double y) {
offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
}
/**
* Draw a point at (x, y).
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
*/
public static void point(double x, double y) {
double r = penRadius;
float scaledPenRadius = (float) (r * DEFAULT_SIZE);
// double ws = factorX(2*r);
// double hs = factorY(2*r);
// if (ws <= 1 && hs <= 1) pixel(x, y);
if (scaledPenRadius <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(scaleX(x) - scaledPenRadius/2,
scaleY(y) - scaledPenRadius/2,
scaledPenRadius, scaledPenRadius));
draw();
}
/**
* Draw a circle of radius r, centered on (x, y).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void circle(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("circle radius must be nonnegative");
ellipse(x, y, r, r);
}
/**
* Draw a filled circle of radius r, centered on (x, y).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void filledCircle(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("circle radius must be nonnegative");
filledEllipse(x, y, r, r);
}
/**
* Draw an ellipse with given semimajor and semiminor axes, centered on (x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
ellipse(x, y, semiMajorAxis, semiMinorAxis, false);
}
/**
* Draw an ellipse with given semimajor and semiminor axes, centered on (x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis, double degrees) {
AffineTransform t = (AffineTransform) offscreen.getTransform();
offscreen.rotate(Math.toRadians(-degrees), scaleX(x), scaleY(y));
ellipse(x, y, semiMajorAxis, semiMinorAxis);
offscreen.setTransform(t);
}
/**
* Draw a filled ellipse with given semimajor and semiminor axes, centered on (x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
ellipse(x, y, semiMajorAxis, semiMinorAxis, true);
}
/**
* Draw a filled ellipse with given semimajor and semiminor axes, centered on (x, y),
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis, double degrees) {
AffineTransform t = (AffineTransform) offscreen.getTransform().clone();
offscreen.rotate(Math.toRadians(-degrees), scaleX(x), scaleY(y));
filledEllipse(x, y, semiMajorAxis, semiMinorAxis);
offscreen.setTransform(t);
}
// helper function for drawing ellipses and filled ellipses
private static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis, boolean filled) {
if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * semiMajorAxis);
double hs = factorY(2 * semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else if (filled) offscreen.fill(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
else offscreen.draw(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
draw();
}
/**
* Draw an arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void arc(double x, double y, double r, double angle1, double angle2) {
arc(x, y, r, angle1, angle2, Arc2D.OPEN, false);
}
/**
* Draw a closed arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void closedArc(double x, double y, double r, double angle1, double angle2) {
arc(x, y, r, angle1, angle2, Arc2D.CHORD, false);
}
/**
* Draw a pie wedge of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void pie(double x, double y, double r, double angle1, double angle2) {
arc(x, y, r, angle1, angle2, Arc2D.PIE, false);
}
/**
* Draw a filled pie wedge of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void filledPie(double x, double y, double r, double angle1, double angle2) {
arc(x, y, r, angle1, angle2, Arc2D.PIE, true);
}
/**
* Draw a filled arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public static void filledArc(double x, double y, double r, double angle1, double angle2) {
arc(x, y, r, angle1, angle2, Arc2D.CHORD, true);
}
// common code for all arc functions
private static void arc(double x, double y, double r, double angle1, double angle2, int pathType, boolean fill) {
if (r < 0) throw new IllegalArgumentException("arc radius must be nonnegative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) {
pixel(x, y);
} else {
if (fill) offscreen.fill(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, pathType));
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, pathType));
}
draw();
}
/**
* Draw a square of side length 2r, centered on (x, y).
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public static void square(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative");
rectangle(x, y, r, r);
}
/**
* Draw a square of side length 2r, centered on (x, y) and rotated counter-clockwise.
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if r is negative
*/
public static void square(double x, double y, double r, double degrees) {
if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative");
rectangle(x, y, r, r, degrees);
}
/**
* Draw a filled square of side length 2r, centered on (x, y).
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public static void filledSquare(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative");
filledRectangle(x, y, r, r);
}
/**
* Draw a filled square of side length 2r, centered on (x, y) and rotated counter-clockwise.
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if r is negative
*/
public static void filledSquare(double x, double y, double r, double degrees) {
if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative");
filledRectangle(x, y, r, r, degrees);
}
/**
* Draw a rectangle of given half width and half height, centered on (x, y).
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
rectangle(x, y, halfWidth, halfHeight, false);
}
/**
* Draw a rectangle of given half width and half height, centered on (x, y) and rotated counter-clockwise.
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void rectangle(double x, double y, double halfWidth, double halfHeight, double degrees) {
AffineTransform t = (AffineTransform) offscreen.getTransform().clone();
offscreen.rotate(Math.toRadians(-degrees), scaleX(x), scaleY(y));
rectangle(x, y, halfWidth, halfHeight);
offscreen.setTransform(t);
}
/**
* Draw a filled rectangle of given half width and half height, centered on (x, y).
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) {
rectangle(x, y, halfWidth, halfHeight, true);
}
/**
* Draw a rectangle of given half width and half height, centered on (x, y) and rotated counter-clockwise.
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @param degrees counter-clockwise rotation by angle degrees around the center
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight, double degrees) {
AffineTransform t = (AffineTransform) offscreen.getTransform();
offscreen.rotate(Math.toRadians(-degrees), scaleX(x), scaleY(y));
filledRectangle(x, y, halfWidth, halfHeight);
offscreen.setTransform(t);
}
private static void rectangle(double x, double y, double halfWidth, double halfHeight, boolean filled) {
if (halfWidth < 0) throw new IllegalArgumentException("half width must be nonnegative");
if (halfHeight < 0) throw new IllegalArgumentException("half height must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * halfWidth);
double hs = factorY(2 * halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else if (filled) offscreen.fill(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
else offscreen.draw(new Rectangle2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
draw();
}
/**
* Draw a polyline with the given (x[i], y[i]) coordinates.
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void polyline(double[] x, double[] y) {
polygon(x, y, false, false);
}
/**
* Draw a polygon with the given (x[i], y[i]) coordinates.
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void polygon(double[] x, double[] y) {
polygon(x, y, true, false);
}
/**
* Draw a filled polygon with the given (x[i], y[i]) coordinates.
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void filledPolygon(double[] x, double[] y) {
polygon(x, y, true, true);
}
private static void polygon(double[] x, double[] y, boolean close, boolean fill) {
int N = x.length;
if (y.length != N)
throw new IllegalArgumentException("x[] and y[] must have the same number of elements. " +
"x[] has " + x.length + " elements, but y[] has " +
y.length + " elements.");
if ((close || fill) && N < 3)
throw new IllegalArgumentException("You must specify at least three for a polygon. " +
"You have only provided " + N + " points.");
Path2D.Double path = new Path2D.Double();
path.moveTo(scaleX(x[0]), scaleY(y[0]));
for (int i = 0; i < N; i++)
path.lineTo(scaleX(x[i]), scaleY(y[i]));
if (close || fill) path.closePath();
if (fill) offscreen.fill(path);
else offscreen.draw(path);
draw();
}
/**
* Draw a polyline with the given coordinates.
* @param coords an array of all the coordindates of the polygon (x1, y1, x2, y2, ...)
* @throws IllegalArgumentException if the number of arguments is not even
*/
public static void polyline(double ... coords) {
polygon(false, false, coords);
}
/**
* Draw a polygon with the given coordinates.
* @param coords an array of all the coordindates of the polygon (x1, y1, x2, y2, ...)
* @throws IllegalArgumentException if the number of arguments is not even and at least 6
*/
public static void polygon(double ... coords) {
polygon(true, false, coords);
}
/**
* Draw a filled polygon with the given coordinates.
* @param coords an array of all the coordindates of the polygon (x1, y1, x2, y2, ...)
* @throws IllegalArgumentException if the number of arguments is not even and at least 6
*/
public static void filledPolygon(double ... coords) {
polygon(true, true, coords);
}
private static void polygon(boolean close, boolean fill, double ... coords) {
int N = coords.length;
if ((N % 2) != 0)
throw new IllegalArgumentException("You must specify an even number of coordinates. " +
"You actually specified " + N + " coordinates.");
// only need at least three vertices for closed/filled polygons
if (close || fill)
if (N < 6)
throw new IllegalArgumentException("You must specify at least six coordinates (three points). " +
"You only specified " + N + " coordinates.");