List of usage examples for java.awt Graphics2D drawString
public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);
From source file:org.squidy.designer.zoom.impl.VisualizationShape.java
/** * @param paintContext//from w w w. jav a2 s .c om */ protected void paintNodeLabels(PPaintContext paintContext) { Graphics2D g = paintContext.getGraphics(); g.setFont(g.getFont().deriveFont(18f)); FontMetrics fm = g.getFontMetrics(); PBounds bounds = getBoundsReference(); double width = bounds.getWidth(); double height = bounds.getHeight(); String inputName = pipeShape.getSource().getTitle(); rotation270.setToRotation(Math.toRadians(270)); paintContext.pushTransform(rotation270); g.setColor(Color.WHITE); g.drawString(inputName, (int) -((height / 2) + (FontUtils.getWidthOfText(fm, inputName) / 2)), -25); paintContext.popTransform(rotation270); String outputName = pipeShape.getTarget().getTitle(); rotation90.setToRotation(Math.toRadians(90)); paintContext.pushTransform(rotation90); g.setColor(Color.WHITE); g.drawString(outputName, (int) ((height / 2) - (FontUtils.getWidthOfText(fm, outputName) / 2)), (int) (-width - 30)); paintContext.popTransform(rotation90); }
From source file:Main.java
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 72); g2.setFont(font);// w w w .j av a 2s .co m String s = "this is a test"; float x = 50, y = 150; // Draw the baseline. FontRenderContext frc = g2.getFontRenderContext(); float width = (float) font.getStringBounds(s, frc).getWidth(); Line2D baseline = new Line2D.Float(x, y, x + width, y); g2.setPaint(Color.red); g2.draw(baseline); // Draw the ascent. LineMetrics lm = font.getLineMetrics(s, frc); Line2D ascent = new Line2D.Float(x, y - lm.getAscent(), x + width, y - lm.getAscent()); g2.draw(ascent); // Draw the descent. Line2D descent = new Line2D.Float(x, y + lm.getDescent(), x + width, y + lm.getDescent()); g2.draw(descent); // Draw the leading. Line2D leading = new Line2D.Float(x, y + lm.getDescent() + lm.getLeading(), x + width, y + lm.getDescent() + lm.getLeading()); g2.draw(leading); // Render the string. g2.setPaint(Color.black); g2.drawString(s, x, y); }
From source file:LineMetricsIllustration.java
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 72); g2.setFont(font);/* w w w .jav a 2 s . com*/ String s = "Java Source and Support"; float x = 50, y = 150; // Draw the baseline. FontRenderContext frc = g2.getFontRenderContext(); float width = (float) font.getStringBounds(s, frc).getWidth(); Line2D baseline = new Line2D.Float(x, y, x + width, y); g2.setPaint(Color.red); g2.draw(baseline); // Draw the ascent. LineMetrics lm = font.getLineMetrics(s, frc); Line2D ascent = new Line2D.Float(x, y - lm.getAscent(), x + width, y - lm.getAscent()); g2.draw(ascent); // Draw the descent. Line2D descent = new Line2D.Float(x, y + lm.getDescent(), x + width, y + lm.getDescent()); g2.draw(descent); // Draw the leading. Line2D leading = new Line2D.Float(x, y + lm.getDescent() + lm.getLeading(), x + width, y + lm.getDescent() + lm.getLeading()); g2.draw(leading); // Render the string. g2.setPaint(Color.black); g2.drawString(s, x, y); }
From source file:net.java.sip.communicator.impl.osdependent.jdic.SystrayServiceJdicImpl.java
private BufferedImage createOverlayImage(String text) { int size = 16; BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //background//from w w w. ja v a 2 s.co m g.setPaint(new Color(0, 0, 0, 102)); g.fillRoundRect(0, 0, size, size, size, size); //filling int mainRadius = 14; g.setPaint(new Color(255, 98, 89)); g.fillRoundRect(size / 2 - mainRadius / 2, size / 2 - mainRadius / 2, mainRadius, mainRadius, size, size); //text Font font = g.getFont(); g.setFont(new Font(font.getName(), Font.BOLD, 9)); FontMetrics fontMetrics = g.getFontMetrics(); int textWidth = fontMetrics.stringWidth(text); g.setColor(Color.white); g.drawString(text, size / 2 - textWidth / 2, size / 2 - fontMetrics.getHeight() / 2 + fontMetrics.getAscent()); return image; }
From source file:com.aurel.track.report.gantt.data.TrackGanttRenderer.java
/** Prints the specified labelstring. If neccessary it reduces the * font size that the label fits in the specified space. * The x coordinate specifies the startposition. * The y coordinate specifies the lower startposition of the label. * If alignRight is true, this method subtracts the length of the * labelstring and 3 pixels from the x coordinate. * Otherwise it adds 3 pixels to the x coordinate. *//*w w w. j a v a 2 s . c om*/ private void drawLabel(String s, Graphics2D g2, int _x, int _y, Font f, boolean alignRight, int space) { g2.setPaint(Color.black); g2.setFont(f); int x = 0; if (alignRight) { // subtract the length neede to print the label from the x coordinate x = _x - g2.getFontMetrics().stringWidth(s) - 3; } else { while (g2.getFontMetrics().stringWidth(s) > space - 4) { log.debug("Reducing Font size for label " + s); f = new Font(f.getName(), f.getStyle(), f.getSize() - 1); g2.setFont(f); } x = _x + 2; } g2.drawString(s, x, _y); }
From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java
/** * Draws an image that can be used as a scale for heat maps generated using * Plot or PlotPyramid.//from w ww.j a v a 2 s .co m * @param output - Output path * @param valueRange - Range of values of interest * @param width - Width of the generated image * @param height - Height of the generated image * @throws IOException */ public static void drawScale(Path output, MinMax valueRange, int width, int height) throws IOException { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setBackground(Color.BLACK); g.clearRect(0, 0, width, height); // fix this part to work according to color1, color2 and gradient type for (int y = 0; y < height; y++) { Color color = NASARectangle.calculateColor(y); g.setColor(color); g.drawRect(width * 3 / 4, y, width / 4, 1); } int fontSize = 24; g.setFont(new Font("Arial", Font.BOLD, fontSize)); int step = (valueRange.maxValue - valueRange.minValue) * fontSize * 10 / height; step = (int) Math.pow(10, Math.round(Math.log10(step))); int min_value = valueRange.minValue / step * step; int max_value = valueRange.maxValue / step * step; for (int value = min_value; value <= max_value; value += step) { int y = fontSize + (height - fontSize) - value * (height - fontSize) / (valueRange.maxValue - valueRange.minValue); g.setColor(Color.WHITE); g.drawString(String.valueOf(value), 5, y); } g.dispose(); FileSystem fs = output.getFileSystem(new Configuration()); FSDataOutputStream outStream = fs.create(output, true); ImageIO.write(image, "png", outStream); outStream.close(); }
From source file:gg.msn.ui.panel.MainPanel.java
@Override public void paint(Graphics g) { super.paint(g); try {//from w w w . ja va 2s . co m Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //render per utenti Facebook if (ChatClientView.protocol.equals(ChatClientView.FACEBOOK_PROTOCOL)) { final FacebookUser user = (FacebookUser) value; int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2); //name string g2.setFont(list.getFont()); g2.drawString(user.name, WHITE_SPACE + IMAGE_LATE + 3, textY); //status string // g2.setFont(list.getFont()); // g2.drawString(user.status, WHITE_SPACE + IMAGE_LATE + 3, textY); //icon ImageIcon icon = user.portrait; //log.debug("icon [" + icon + "]"); //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING)); g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, null); // g2.setColor(Color.WHITE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, ARC_SIZE, ARC_SIZE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+1) / 2), IMAGE_LATE+1, IMAGE_LATE+1, ARC_SIZE, ARC_SIZE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+2) / 2), IMAGE_LATE+2, IMAGE_LATE+2, ARC_SIZE, ARC_SIZE); //render per utenti Client // log.debug("user status [" + user.status + "]"); // log.debug("user online status [" + user.onlineStatus + "]"); if (StringUtils.equals(user.status, FacebookUser.STATUS_ONLINE)) { g2.setColor(Color.GREEN); g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2), STATUS_ICON_WIDTH, STATUS_ICON_WIDTH); } else { g2.setColor(Color.GRAY); g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2), STATUS_ICON_WIDTH, STATUS_ICON_WIDTH); } } else { g2.setFont(list.getFont()); int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2); Client client = (Client) value; // setText((client).getNick()); ImageIcon icon = null; try { new ImageIcon(client.getImage()); } catch (Exception e) { // log.debug("immgine non presente"); icon = ThemeManager.getTheme().get(ThemeManager.USER_ICON); } g2.drawString(client.getNick(), WHITE_SPACE + IMAGE_LATE + 3, textY); //log.debug("icon [" + icon + "]"); //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING)); g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, null); // setFont(list.getFont()); // setIcon(scaledIcon); } } catch (Exception e) { log.warn(e); } }
From source file:com.aurel.track.report.gantt.data.TrackGanttRenderer.java
/** Prints the specified labelstring. * The x coordinate specifies the startposition. * The y coordinate specifies the lower startposition of the label. * If alignRight is true, this method subtracts the length of the * labelstring and 3 pixels from the x coordinate. * Otherwise it adds 3 pixels to the x coordinate. *///from w w w . j av a2 s. c om private void drawLabel(String s, Graphics2D g2, int _x, int _y, Font f, boolean alignRight) { g2.setPaint(Color.black); g2.setFont(f); int x = 0; if (alignRight) { // subtract the length neede to print the label from the x coordinate x = _x - g2.getFontMetrics().stringWidth(s) - 3; } else { x = _x + 3; } // correct the very first and very last point in the diagram. if (startLabels > x) { startLabels = x; } if (stopLabels < x + g2.getFontMetrics().stringWidth(s)) { stopLabels = x + g2.getFontMetrics().stringWidth(s); } g2.drawString(s, x, _y); }
From source file:org.uva.itast.blended.omr.scanners.BarcodeScanner.java
/** * @param campo//w ww. ja v a2 s .c o m */ public void markBarcode(Field campo) { try { //get bbox in pixels Rectangle rect = pageImage.toPixels(campo.getBBox()); // expand the area for some tolerance Rectangle2D expandedArea = getExpandedArea(campo.getBBox(), (float) BARCODE_AREA_PERCENT); Rectangle expandedRect = pageImage.toPixels(expandedArea); Graphics2D g = pageImage.getReportingGraphics(); AffineTransform t = g.getTransform(); g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1, new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0)); if (lastResult != null) g.setColor(Color.BLUE); else g.setColor(Color.RED); g.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 3, 3); g.drawRoundRect(expandedRect.x, expandedRect.y, expandedRect.width, expandedRect.height, 3, 3); g.setFont(new Font("Arial", Font.BOLD, (int) (12 / t.getScaleX()))); String message; if (lastResult != null) message = ((Result) lastResult.getResult()).getBarcodeFormat().toString() + "=" + getParsedCode(lastResult); else message = "UNRECOGNIZED!"; g.drawString(message, rect.x, rect.y); } catch (Exception e) { logger.error("Unexpected errr while logging the image:", e); } }
From source file:com.imag.nespros.gui.plugin.GraphEditor.java
/** * create an instance of a simple graph with popup controls to create a * graph./*from w w w .j a v a 2s . c o m*/ * */ private GraphEditor(Simulation s) { simu = s; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { Logger.getLogger(GraphEditor.class.getName()).log(Level.SEVERE, null, ex); } // create a simple graph for the demo graph = Topology.getInstance().getGraph(); this.layout = new StaticLayout<Device, ComLink>(graph, new Transformer<Device, Point2D>() { @Override public Point2D transform(Device v) { Point2D p = new Point2D.Double(v.getX(), v.getY()); return p; } }, new Dimension(600, 600)); vv = new VisualizationViewer<Device, ComLink>(layout); vv.setBackground(Color.white); final Transformer<Device, String> vertexLabelTransformer = new Transformer<Device, String>() { @Override public String transform(Device d) { return d.getDeviceName(); } }; //vv.getRenderContext().setVertexLabelTransformer(MapTransformer.<Device, String>getInstance( // LazyMap.<Device, String>decorate(new HashMap<Device, String>(), new ToStringLabeller<Device>()))); vv.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer); vv.getRenderContext().setEdgeLabelTransformer(new Transformer<ComLink, String>() { @Override public String transform(ComLink link) { return (link.getID() + ", " + link.getLatency()); } }); //float dash[] = {0.1f}; //final Stroke edgeStroke = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 1.0f); final Stroke edgeStroke = new BasicStroke(3.0f); final Transformer<ComLink, Stroke> edgeStrokeTransformer = new Transformer<ComLink, Stroke>() { @Override public Stroke transform(ComLink l) { return edgeStroke; } }; Transformer<ComLink, Paint> edgePaint = new Transformer<ComLink, Paint>() { public Paint transform(ComLink l) { if (l.isDown()) { return Color.RED; } else { return Color.BLACK; } } }; vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint); vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); vv.setVertexToolTipTransformer(vv.getRenderContext().getVertexLabelTransformer()); vv.getRenderContext().setVertexIconTransformer(new CustomVertexIconTransformer()); vv.getRenderContext().setVertexShapeTransformer(new CustomVertexShapeTransformer()); vv.addPreRenderPaintable(new VisualizationViewer.Paintable() { @Override public void paint(Graphics grphcs) { for (Device d : Topology.getInstance().getGraph().getVertices()) { int size = d.getOperators().size(); MyLayeredIcon icon = d.getIcon(); //if(icon == null) continue; icon.removeAll(); if (size > 0) { // the vertex icon // Let's create the annotation image to be added to icon.. BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.ORANGE); g.fillOval(0, 0, 20, 20); g.setColor(Color.BLACK); g.drawString(size + "", 5, 13); g.dispose(); ImageIcon img = new ImageIcon(image); //Dimension id = new Dimension(icon.getIconWidth(), icon.getIconHeight()); //double x = vv.getModel().getGraphLayout().transform(d).getX(); //x -= (icon.getIconWidth() / 2); //double y = vv.getModel().getGraphLayout().transform(d).getY(); //y -= (icon.getIconHeight() / 2); //grphcs.drawImage(image, (int) Math.round(x), (int) Math.round(y), null); icon.add(img); } } } @Override public boolean useTransform() { return false; } }); Container content = getContentPane(); final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); content.add(panel); Factory<Device> vertexFactory = DeviceFactory.getInstance(); Factory<ComLink> edgeFactory = ComLinkFactory.getInstance(); final EditingModalGraphMouse<Device, ComLink> graphMouse = new EditingModalGraphMouse<>( vv.getRenderContext(), vertexFactory, edgeFactory); // Trying out our new popup menu mouse plugin... PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin(); // Add some popup menus for the edges and vertices to our mouse plugin. JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame); JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu(frame); myPlugin.setEdgePopup(edgeMenu); myPlugin.setVertexPopup(vertexMenu); graphMouse.remove(graphMouse.getPopupEditingPlugin()); // Removes the existing popup editing plugin graphMouse.add(myPlugin); // Add our new plugin to the mouse // AnnotatingGraphMousePlugin<Device,ComLink> annotatingPlugin = // new AnnotatingGraphMousePlugin<>(vv.getRenderContext()); //graphMouse.add(annotatingPlugin); // the EditingGraphMouse will pass mouse event coordinates to the // vertexLocations function to set the locations of the vertices as // they are created // graphMouse.setVertexLocations(vertexLocations); vv.setGraphMouse(graphMouse); vv.addKeyListener(graphMouse.getModeKeyListener()); graphMouse.setMode(ModalGraphMouse.Mode.PICKING); //final ImageAtEdgePainter<String, String> imageAtEdgePainter = // new ImageAtEdgePainter<String, String>(vv, edge, image); final ScalingControl scaler = new CrossoverScalingControl(); JButton plus = new JButton("+"); plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); } }); JButton minus = new JButton("-"); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1 / 1.1f, vv.getCenter()); } }); JButton help = new JButton("Help"); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(vv, instructions); } }); JButton deploy = new JButton("Deploy"); deploy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // OPMapping algo here if (simu == null) { return; } GraphUtil<Device, ComLink> util = new GraphUtil<>(); for (EventProducer p : simu.getProducers()) { if (!p.isMapped()) { JOptionPane.showMessageDialog(frame, "Cannot map operators. Please deploy the producer: " + p.getName()); return; } } for (EventConsumer c : simu.getConsumers()) { if (!c.isMapped()) { JOptionPane.showMessageDialog(frame, "Cannot map operators. Please deploy the consumer: " + c.getName()); return; } System.out.println("-- Operator placement algorithm Greedy: " + c.getName() + " --"); Solution init = util.initialMapping(c.getGraph()); System.out.println(c.getGraph() + "\nInitial Mapping: " + init); OperatorMapping mapper = new OperatorMapping(); long T1, T2; System.out.println("--- OpMapping Algo Greedy --- "); T1 = System.currentTimeMillis(); Solution solution = mapper.opMapping(c.getGraph(), Topology.getInstance().getGraph(), init); T2 = System.currentTimeMillis(); System.out.println(solution); System.out.println("Solution founded in: " + (T2 - T1) + " ms"); } // Solution init = util.initialMapping(EPGraph.getInstance().getGraph()); // System.out.println("Initial Mapping: " + init); // OperatorMapping mapper = new OperatorMapping(); // long T1, T2; // System.out.println("--- OpMapping Algo Greedy --- "); // T1 = System.currentTimeMillis(); // Solution solution = mapper.opMapping(EPGraph.getInstance().getGraph(), // Topology.getInstance().getGraph(), init); // T2 = System.currentTimeMillis(); // System.out.println(solution); // System.out.println("Solution founded in: " + (T2 - T1) + " ms"); vv.repaint(); } }); JButton run = new JButton("Run"); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // run the simulation here System.out.println("Setting the simulation..."); for (EventConsumer c : simu.getConsumers()) { for (EPUnit op : c.getGraph().getVertices()) { if (op.isMapped()) { op.openIOchannels(); } else { JOptionPane.showMessageDialog(frame, "Cannot run, undeployed operators founded."); return; } } } //ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); System.out.println("Running the simulation..."); //scheduledExecutorService.execute(runner); for (Device device : Topology.getInstance().getGraph().getVertices()) { if (!device.isAlive()) { device.start(); } } for (ComLink link : Topology.getInstance().getGraph().getEdges()) { if (!link.isAlive()) { link.start(); } } for (EventConsumer c : simu.getConsumers()) { for (EPUnit op : c.getGraph().getVertices()) { if (op.isMapped() && op.getDevice() != null && !op.isAlive()) { op.start(); } } } } }); AnnotationControls<Device, ComLink> annotationControls = new AnnotationControls<Device, ComLink>( graphMouse.getAnnotatingPlugin()); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 0); slider.setMinorTickSpacing(5); slider.setMajorTickSpacing(30); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setLabelTable(slider.createStandardLabels(15)); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); if (!slider.getValueIsAdjusting()) { speedSimulation(slider.getValue()); } } }); JPanel controls = new JPanel(); controls.add(plus); controls.add(minus); JComboBox modeBox = graphMouse.getModeComboBox(); controls.add(modeBox); controls.add(annotationControls.getAnnotationsToolBar()); controls.add(slider); controls.add(deploy); controls.add(run); controls.add(help); content.add(controls, BorderLayout.SOUTH); /* Custom JPanels can be added here */ // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //final GraphEditor demo = new GraphEditor(); }