List of usage examples for java.awt Graphics2D setFont
public abstract void setFont(Font font);
From source file:spinworld.gui.RadarPlot.java
private void drawTickLabel(Graphics2D g2, Rectangle2D radarArea, Point2D middlePoint, double _axisAngle, int cat, double tick) { double axisAngle = normalize(_axisAngle); double _origin = getOrigin(cat).doubleValue(); double max = getMaxValue(cat).doubleValue(); double tickValue = ((max - _origin) * tick) + _origin; String label = "" + Math.round(tickValue * 1000) / 1000d; FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); int labelW = (int) labelBounds.getWidth(); int labelH = (int) labelBounds.getHeight(); double centerX = radarArea.getCenterX(); double centerY = radarArea.getCenterY(); double adj = middlePoint.distance(centerX, centerY); double opp = TICK_MARK_LENGTH / 2 + 4; double hyp = Math.sqrt(Math.pow(opp, 2) + Math.pow(adj, 2)); double angle = Math.toDegrees(Math.atan(opp / adj)); int charHeight = g2.getFontMetrics().getHeight(); int charWidth = g2.getFontMetrics().charWidth('M'); double alphaRad = Math.toRadians(axisAngle - angle); double labelX = centerX + (hyp * Math.cos(alphaRad)); double labelY = centerY - (hyp * Math.sin(alphaRad)) + labelH; // g2.draw(new Line2D.Double(centerX, centerY, labelX, labelY - labelH)); // test line double sinGap = Math.pow(Math.sin(Math.toRadians(axisAngle)), 2); if (axisAngle > 90 && axisAngle < 270) { labelY -= labelH;/*from ww w . j a v a 2 s. c om*/ labelY += (charHeight * sinGap / 2); } else { labelY -= (charHeight * sinGap / 2); } double cosGap = Math.pow(Math.cos(Math.toRadians(axisAngle)), 2); if (axisAngle > 180) { labelX -= labelW; labelX += (charWidth * cosGap / 2); } else { labelX -= (charWidth * cosGap / 2); } // g2.drawRect((int) labelX, (int) labelY - labelH, labelW, labelH); // test rectangle g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelX, (float) labelY); }
From source file:be.fedict.eidviewer.gui.printing.IDPrintout.java
public int print(Graphics graphics, PageFormat pageFormat, int pageNumber) throws PrinterException { // we only support printing all in one single page if (pageNumber > 0) return Printable.NO_SUCH_PAGE; logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("width", pageFormat.getWidth()).append("height", pageFormat.getHeight()) .append("imageableWidth", pageFormat.getImageableWidth()) .append("imageableHeight", pageFormat.getImageableHeight()) .append("imageableX", pageFormat.getImageableX()).append("imageableY", pageFormat.getImageableY()) .append("orientation", pageFormat.getOrientation()) .append("paper.width", pageFormat.getPaper().getWidth()) .append("paper.height", pageFormat.getPaper().getHeight()) .append("paper.imageableWidth", pageFormat.getPaper().getImageableWidth()) .append("paper.imageableHeight", pageFormat.getPaper().getImageableHeight()) .append("paper.imageableX", pageFormat.getPaper().getImageableX()) .append("paper.imageableY", pageFormat.getPaper().getImageableY()).toString()); logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("clip.width", graphics.getClipBounds().width) .append("clip.height", graphics.getClipBounds().height).append("clip.x", graphics.getClipBounds().x) .append("clip.y", graphics.getClipBounds().y).toString()); // translate graphics2D with origin at top left first imageable location Graphics2D graphics2D = (Graphics2D) graphics; graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // keep imageable width and height as variables for clarity (we use them often) float imageableWidth = (float) pageFormat.getImageableWidth(); float imageableHeight = (float) pageFormat.getImageableHeight(); // Coat of Arms images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI AffineTransform coatOfArmsTransform = new AffineTransform(); coatOfArmsTransform.scale(0.5, 0.5); // photo images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI AffineTransform photoTransform = new AffineTransform(); photoTransform.scale(0.5, 0.5);/*from ww w .j a v a 2 s. c om*/ photoTransform.translate((imageableWidth * 2) - (photo.getWidth(this)), 0); // make sure foreground is black, and draw coat of Arms and photo at the top of the page // using the transforms to scale them to 72DPI. graphics2D.setColor(Color.BLACK); graphics2D.drawImage(coatOfArms, coatOfArmsTransform, null); graphics2D.drawImage(photo, photoTransform, null); // calculate some sizes that need to take into account the scaling of the graphics, to avoid dragging // those non-intuitive "/2" further along in the code. float headerHeight = (float) (coatOfArms.getHeight(this)) / 2; float coatOfArmsWidth = (float) (coatOfArms.getWidth(this)) / 2; float photoWidth = (float) (photo.getWidth(this)) / 2; float headerSpaceBetweenImages = imageableWidth - (coatOfArmsWidth + photoWidth + (SPACE_BETWEEN_ITEMS * 2)); logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("headerHeight", headerHeight) .append("coatOfArmsWidth", coatOfArmsWidth).append("photoWidth", photoWidth) .append("headerSpaceBetweenImages", headerSpaceBetweenImages).toString()); // get localised strings for card type. We'll take a new line every time a ";" is found in the resource String[] cardTypeStr = (bundle.getString("type_" + this.identity.getDocumentType().toString()) .toUpperCase()).split(";"); // if a "mention" is present, append it so it appears below the card type string, between brackets if (identity.getSpecialOrganisation() != SpecialOrganisation.UNSPECIFIED) { String mention = TextFormatHelper.getSpecialOrganisationString(bundle, identity.getSpecialOrganisation()); if (mention != null && !mention.isEmpty()) { String[] cardTypeWithMention = new String[cardTypeStr.length + 1]; System.arraycopy(cardTypeStr, 0, cardTypeWithMention, 0, cardTypeStr.length); cardTypeWithMention[cardTypeStr.length] = "(" + mention + ")"; cardTypeStr = cardTypeWithMention; } } // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the card type strings // stop when a font size is found where they all fit the space between the graphics in an orderly manner boolean sizeFound = false; int fontSize; for (fontSize = TITLE_MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely { logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound); graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize)); sizeFound = (ImageUtilities.getTotalStringWidth(graphics2D, cardTypeStr) < headerSpaceBetweenImages) && (ImageUtilities.getTotalStringHeight(graphics2D, cardTypeStr) < headerHeight); } // unless with extremely small papers, a size should always have been found. // draw the card type strings, centered, between the images at the top of the page if (sizeFound) { graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize + 1)); float cardTypeHeight = cardTypeStr.length * ImageUtilities.getStringHeight(graphics2D); float cardTypeBaseLine = ((headerHeight - cardTypeHeight) / 2) + ImageUtilities.getAscent(graphics2D); float cardTypeLineHeight = ImageUtilities.getStringHeight(graphics2D); logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("cardTypeHeight", cardTypeHeight).append("cardTypeBaseLine", cardTypeBaseLine) .append("cardTypeLineHeight", cardTypeLineHeight).toString()); for (int i = 0; i < cardTypeStr.length; i++) { float left = (coatOfArmsWidth + SPACE_BETWEEN_ITEMS + (headerSpaceBetweenImages - ImageUtilities.getStringWidth(graphics2D, cardTypeStr[i])) / 2); float leading = (float) cardTypeLineHeight * i; graphics2D.drawString(cardTypeStr[i], left, cardTypeBaseLine + leading); } } // populate idAttributes with all the information from identity and address // as well as date printed and some separators List<IdentityAttribute> idAttributes = populateAttributeList(); // draw a horizontal line just below the header (images + card type titles) graphics2D.drawLine(0, (int) headerHeight, (int) imageableWidth, (int) headerHeight); // calculate how much space is left between the header and the bottom of the imageable area headerHeight += 32; // take some distance from header float imageableDataHeight = imageableHeight - headerHeight; float totalDataWidth = 0, totalDataHeight = 0; float labelWidth, widestLabelWidth = 0; float valueWidth, widestValueWidth = 0; // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the information in idAttributes into // the space between the header and the bottom of the imageable area // stop when a font size is found where it all fits in an orderly manner sizeFound = false; for (fontSize = MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely { logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound); graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize)); widestLabelWidth = 0; widestValueWidth = 0; for (IdentityAttribute attribute : idAttributes) { if (attribute == SEPARATOR) continue; labelWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getLabel()); valueWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getValue()); if (labelWidth > widestLabelWidth) widestLabelWidth = labelWidth; if (valueWidth > widestValueWidth) widestValueWidth = valueWidth; } totalDataWidth = widestLabelWidth + SPACE_BETWEEN_ITEMS + widestValueWidth; totalDataHeight = ImageUtilities.getStringHeight(graphics2D) + (ImageUtilities.getStringHeight(graphics2D) * idAttributes.size()); if ((totalDataWidth < imageableWidth) && (totalDataHeight < imageableDataHeight)) sizeFound = true; } logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("widestLabelWidth", widestLabelWidth).append("widestValueWidth", widestValueWidth) .append("totalDataWidth", totalDataWidth).append("totalDataHeight", totalDataHeight).toString()); // unless with extremely small papers, a size should always have been found. // draw the identity, addess and date printed information, in 2 columns, centered inside the // space between the header and the bottom of the imageable area if (sizeFound) { graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize)); float labelsLeft = (imageableWidth - totalDataWidth) / 2; float valuesLeft = labelsLeft + widestLabelWidth + SPACE_BETWEEN_ITEMS; float dataLineHeight = ImageUtilities.getStringHeight(graphics2D); float dataTop = dataLineHeight + headerHeight + ((imageableDataHeight - totalDataHeight) / 2); float lineNumber = 0; logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("labelsLeft", labelsLeft) .append("valuesLeft", valuesLeft).append("dataLineHeight", dataLineHeight) .append("dataTop", dataTop).toString()); for (IdentityAttribute attribute : idAttributes) { if (attribute != SEPARATOR) // data { graphics2D.setColor(attribute.isRelevant() ? Color.BLACK : Color.LIGHT_GRAY); graphics2D.drawString(attribute.getLabel(), labelsLeft, dataTop + (lineNumber * dataLineHeight)); graphics2D.drawString(attribute.getValue(), valuesLeft, dataTop + (lineNumber * dataLineHeight)); } else // separator { int y = (int) (((dataTop + (lineNumber * dataLineHeight) + (dataLineHeight / 2))) - ImageUtilities.getAscent(graphics2D)); graphics2D.setColor(Color.BLACK); graphics2D.drawLine((int) labelsLeft, y, (int) (labelsLeft + totalDataWidth), y); } lineNumber++; } } // tell Java printing that all this makes for a page worth printing :-) return Printable.PAGE_EXISTS; }
From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private BufferedImage createFloorImage(HmFolder floor, double scale, int floorWidth, int floorHeight, Map<Long, Integer> channelMap, Map<Long, Integer> colorMap, int borderX, int borderY, double gridSize) throws Exception { BufferedImage image = new BufferedImage(floorWidth + borderX + 1, floorHeight + borderY + 1, BufferedImage.TYPE_INT_ARGB); if (floor == null) { return image; }// www . j av a 2 s . c o m double metricWidth = 0.0, metricHeight = 0.0, offsetX = 0.0, offsetY = 0.0; int imageWidth = 0; LengthUnit lengthUnit = LengthUnit.METERS; if (null != floor.getMetricWidth()) { metricWidth = floor.getMetricWidth().doubleValue(); } if (null != floor.getMetricHeight()) { metricHeight = floor.getMetricHeight().doubleValue(); } if (null != floor.getImageWidth()) { imageWidth = floor.getImageWidth().intValue(); } if (null != floor.getOffsetX()) { offsetX = floor.getOffsetX().doubleValue(); } if (null != floor.getOffsetY()) { offsetY = floor.getOffsetY().doubleValue(); } if (null != floor.getLengthUnit()) { lengthUnit = floor.getLengthUnit(); } Graphics2D g2 = image.createGraphics(); g2.setStroke(new BasicStroke(1)); if (getDistanceMetric(metricWidth, lengthUnit) == 0) { g2.setColor(new Color(255, 255, 255)); g2.fillRect(borderX, 0, floorWidth + 1, borderY); g2.fillRect(0, 0, borderX, borderY + floorHeight + 1); g2.setColor(new Color(120, 120, 120)); g2.drawLine(0, borderY, floorWidth + borderX, borderY); g2.drawLine(borderX, 0, borderX, floorHeight + borderY); g2.setColor(new Color(255, 255, 204)); g2.fillRect(borderX + 2, borderY + 2, 162, 25); g2.setColor(new Color(0, 51, 102)); g2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12)); g2.drawString("Please size this floor plan.", borderX + 8, borderY + 19); return image; } double screenWidth = scale * getDistanceMetric(metricWidth, lengthUnit); double imageScale = screenWidth / imageWidth; int originX = (int) (getDistanceMetric(offsetX, lengthUnit) * scale); int originY = (int) (getDistanceMetric(offsetY, lengthUnit) * scale); g2.setColor(new Color(255, 255, 255)); if (floor.getBackground() != null && floor.getBackground().length() > 0) { LinkedMultiValueMap<String, String> metadata = new LinkedMultiValueMap<>(); String url = getImageBaseUrl(floor.getOwnerId()) + floor.getBackground(); try { BufferedImage map = ImageIO.read(clientFileService.getFile(url, "AFS_TOKEN", metadata)); AffineTransform transform = new AffineTransform(); transform.scale(imageScale, imageScale); g2.drawImage(map, new AffineTransformOp(transform, null), getFloorX(0, borderX, originX), getFloorY(0, borderY, originY)); } catch (Exception e) { logger.error(String.format("image file not found with url: %s", url)); double screenHeight = scale * getDistanceMetric(metricHeight, lengthUnit); g2.fillRect(getFloorX(0, borderX, originX), getFloorY(0, borderY, originY), (int) screenWidth, (int) screenHeight); } } else { double screenHeight = scale * getDistanceMetric(metricHeight, lengthUnit); g2.fillRect(getFloorX(0, borderX, originX), getFloorY(0, borderY, originY), (int) screenWidth, (int) screenHeight); } g2.setColor(new Color(204, 204, 204)); // Right edge border g2.drawLine(borderX + floorWidth, borderY + 1, borderX + floorWidth, borderY + floorHeight); // Left edge border (right of tick marks) g2.drawLine(borderX + 1, borderY + floorHeight, borderX + floorWidth, borderY + floorHeight); g2.setColor(new Color(255, 255, 255)); g2.fillRect(borderX, 0, floorWidth + 1, borderY); g2.fillRect(0, 0, borderX, borderY + floorHeight + 1); g2.setColor(new Color(120, 120, 120)); g2.drawLine(0, borderY, floorWidth + borderX, borderY); g2.drawLine(borderX, 0, borderX, floorHeight + borderY); Font font = new Font(Font.SANS_SERIF, Font.BOLD, 12); double actualWidth = floorWidth / scale; double actualHeight = floorHeight / scale; String firstLabel; double unitScale = scale; if (LengthUnit.FEET == lengthUnit) { firstLabel = "0 feet"; actualWidth /= HmFolder.FEET_TO_METERS; actualHeight /= HmFolder.FEET_TO_METERS; unitScale *= HmFolder.FEET_TO_METERS; } else { firstLabel = "0 meters"; } g2.drawString(firstLabel, borderX + 4, 12); double gridX = gridSize; while (gridX < actualWidth) { int x = (int) (gridX * unitScale) + borderX; g2.drawLine(x, 0, x, borderY); boolean label = true; if (gridX + gridSize >= actualWidth) { // Last mark if (x + getNumberPixelWidth(gridX) + 2 > floorWidth) { label = false; } } if (label) { g2.drawString("" + (int) gridX, x + 4, 12); } gridX += gridSize; } double gridY = 0; while (gridY < actualHeight) { int y = (int) (gridY * unitScale) + borderY; g2.drawLine(0, y, borderX, y); double lx = gridY; int dx = 1; for (int bx = borderX; bx >= 16; bx -= 7) { if (lx < 10) { dx += 7; } else { lx /= 10; } } boolean label = true; if (gridY + gridSize >= actualHeight) { // Last mark if (y - borderY + 13 > floorHeight) { label = false; } } if (label) { g2.drawString("" + (int) gridY, dx, y + 13); } gridY += gridSize; } double mapToImage = getMapToMetric(metricWidth, imageWidth, lengthUnit) * scale; if (floor.getPerimeter().size() > 0) { g2.setStroke(new BasicStroke(2)); g2.setColor(new Color(2, 159, 245)); int[] xPoints = new int[floor.getPerimeter().size()]; int[] yPoints = new int[floor.getPerimeter().size()]; int nPoints = 0; int perimId = floor.getPerimeter().get(0).getId(); for (int i = 0; i < floor.getPerimeter().size(); i++) { HmVertex vertex = floor.getPerimeter().get(i); if (vertex.getId() != perimId) { g2.drawPolygon(xPoints, yPoints, nPoints); nPoints = 0; perimId = vertex.getId(); } xPoints[nPoints] = getFloorX((int) (vertex.getX() * mapToImage), borderX, originX); yPoints[nPoints++] = getFloorY((int) (vertex.getY() * mapToImage), borderY, originY); } g2.drawPolygon(xPoints, yPoints, nPoints); } g2.setStroke(new BasicStroke(1)); g2.setColor(new Color(0, 170, 0)); g2.setFont(font.deriveFont(Font.BOLD, 11)); List<HmDeviceLocationEx> devices = deviceLocationExRep.findAllHmDevices(floor.getId()); if (null != devices && !devices.isEmpty()) { for (HmDeviceLocationEx device : devices) { double x = device.getX() * mapToImage; double y = device.getY() * mapToImage; createNodeImage(device.getId(), channelMap, colorMap, getFloorX((int) x, borderX, originX), getFloorY((int) y, borderY, originY), g2); } } else { List<HmDevicePlanningEx> plannedDevices = devicePlanningExRep.findAllPlannedDevices(floor.getId()); for (HmDevicePlanningEx plannedDevice : plannedDevices) { double x = plannedDevice.getX() * mapToImage; double y = plannedDevice.getY() * mapToImage; createNodeImage(plannedDevice.getId(), channelMap, colorMap, getFloorX((int) x, borderX, originX), getFloorY((int) y, borderY, originY), g2); } } return image; }
From source file:SWT2D.java
private void run() { // Create top level shell final Display display = new Display(); final Shell shell = new Shell(display); shell.setText("Java 2D Example"); // GridLayout for canvas and button shell.setLayout(new GridLayout()); // Create container for AWT canvas final Composite canvasComp = new Composite(shell, SWT.EMBEDDED); // Set preferred size GridData data = new GridData(); data.widthHint = 600;//from w w w .j a va 2 s. co m data.heightHint = 500; canvasComp.setLayoutData(data); // Create AWT Frame for Canvas java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp); // Create Canvas and add it to the Frame final java.awt.Canvas canvas = new java.awt.Canvas(); canvasFrame.add(canvas); // Get graphical context and cast to Java2D final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas.getGraphics(); // Enable antialiasing g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Remember initial transform final java.awt.geom.AffineTransform origTransform = g2d.getTransform(); // Create Clear button and position it Button clearButton = new Button(shell, SWT.PUSH); clearButton.setText("Clear"); data = new GridData(); data.horizontalAlignment = GridData.CENTER; clearButton.setLayoutData(data); // Event processing for Clear button clearButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Delete word list and redraw canvas wordList.clear(); canvasComp.redraw(); } }); // Process canvas mouse clicks canvas.addMouseListener(new java.awt.event.MouseListener() { public void mouseClicked(java.awt.event.MouseEvent e) { } public void mouseEntered(java.awt.event.MouseEvent e) { } public void mouseExited(java.awt.event.MouseEvent e) { } public void mousePressed(java.awt.event.MouseEvent e) { // Manage pop-up editor display.syncExec(new Runnable() { public void run() { if (eShell == null) { // Create new Shell: non-modal! eShell = new Shell(shell, SWT.NO_TRIM | SWT.MODELESS); eShell.setLayout(new FillLayout()); // Text input field eText = new Text(eShell, SWT.BORDER); eText.setText("Text rotation in the SWT?"); eShell.pack(); // Set position (Display coordinates) java.awt.Rectangle bounds = canvas.getBounds(); org.eclipse.swt.graphics.Point pos = canvasComp.toDisplay(bounds.width / 2, bounds.height / 2); Point size = eShell.getSize(); eShell.setBounds(pos.x, pos.y, size.x, size.y); // Open Shell eShell.open(); } else if (!eShell.isVisible()) { // Editor versteckt, sichtbar machen eShell.setVisible(true); } else { // Editor is visible - get text String t = eText.getText(); // set editor invisible eShell.setVisible(false); // Add text to list and redraw canvas wordList.add(t); canvasComp.redraw(); } } }); } public void mouseReleased(java.awt.event.MouseEvent e) { } }); // Redraw the canvas canvasComp.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { // Pass the redraw task to AWT event queue java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // Compute canvas center java.awt.Rectangle bounds = canvas.getBounds(); int originX = bounds.width / 2; int originY = bounds.height / 2; // Reset canvas g2d.setTransform(origTransform); g2d.setColor(java.awt.Color.WHITE); g2d.fillRect(0, 0, bounds.width, bounds.height); // Set font g2d.setFont(new java.awt.Font("Myriad", java.awt.Font.PLAIN, 32)); double angle = 0d; // Prepare star shape double increment = Math.toRadians(30); Iterator iter = wordList.iterator(); while (iter.hasNext()) { // Determine text colors in RGB color cycle float red = (float) (0.5 + 0.5 * Math.sin(angle)); float green = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(120))); float blue = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(240))); g2d.setColor(new java.awt.Color(red, green, blue)); // Redraw text String text = (String) iter.next(); g2d.drawString(text, originX + 50, originY); // Rotate for next text output g2d.rotate(increment, originX, originY); angle += increment; } } }); } }); // Finish shell and open it shell.pack(); shell.open(); // SWT event processing while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:net.sf.firemox.clickable.target.card.VirtualCard.java
@SuppressWarnings("null") @Override// w ww.ja v a 2s . co m public void paintComponent(Graphics g) { final Graphics2D g2D = (Graphics2D) g; // Renderer g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // Optimization card painting final MZone container = card.getContainer(); final boolean shortPaint = container == null || !container.isMustBePainted(card); // tap/reverse operation : PI/2, PI, -PI/2 rotation if (!shortPaint) { if (container.isMustBePaintedReversed(card)) { if (card.tapped) { g2D.translate(rotateTransformY, CardFactory.cardWidth + rotateTransformX); g2D.rotate(angle - Math.PI / 2); } else { g2D.translate(CardFactory.cardWidth + rotateTransformX, CardFactory.cardHeight + rotateTransformY); g2D.rotate(Math.PI - angle); } } else { if (card.tapped) { g2D.translate(CardFactory.cardHeight + rotateTransformY, rotateTransformX); g2D.rotate(Math.PI / 2 + angle); } else { g2D.translate(rotateTransformX, rotateTransformY); g2D.rotate(angle); } } } if (container != null) { if (container.isVisibleForOpponent() && !card.isVisibleForOpponent() && card.isVisibleForYou()) { /* * This card is visible for you but not for opponent in despite of the * fact the container is public. */ g2D.drawImage(card.scaledImage(), null, null); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g2D.drawImage(DatabaseFactory.scaledBackImage, null, null); } else if (!card.isVisibleForYou()) { g2D.drawImage(DatabaseFactory.scaledBackImage, null, null); } else { g2D.drawImage(card.scaledImage(), null, null); } } if (shortPaint) return; /* * The card picture is displayed as a rounded rectangle with 0,90,180 or * 270 */ if (card.isHighLighted && (card.isVisibleForYou() || StackManager.idHandedPlayer == 0)) { // Draw the rounded colored rectangle g2D.setColor(card.highLightColor); g2D.draw3DRect(0, 0, CardFactory.cardWidth - 2, CardFactory.cardHeight - 2, false); } // Draw the eventual progress bar card.database.updatePaintNotification(card, g); // Cursor for our pretty pictures int px = 3; int py = 3; int maxX = CardFactory.cardWidth - 2; // for in-play, visible cards if (card.isVisibleForYou() || (container != null && container.isVisibleForYou())) { // draw registers above the card's picture if (refreshToolTipFilter().powerANDtoughness) { // power / toughness final String powerANDtoughness = String.valueOf(card.getValue(IdTokens.POWER)) + "/" + card.getValue(IdTokens.TOUGHNESS); g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 13)); final Rectangle2D stringDim = g2D.getFontMetrics().getStringBounds(powerANDtoughness, g2D); g2D.setColor(CardFactory.powerToughnessColor); g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3), CardFactory.cardHeight - 5); g2D.setColor(Color.BLUE); g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3), CardFactory.cardHeight - 6); } /* * START drawing additional pictures */ // draw state pictures for (StatePicture statePicture : CardFactory.statePictures) { if (px + 13 > maxX) { px = 3; py += 13; } if (statePicture.paint(card, g2D, px, py)) { px += 13; } } // draw properties if (card.cachedProperties != null) { for (Integer property : card.cachedProperties) { if (Configuration.getBoolean("card.property.picture", true) && CardFactory.propertyPictures.get(property) != null) { // There is an associated picture to this property if (px + 13 > maxX) { px = 3; py += 13; } g2D.drawImage(CardFactory.propertyPictures.get(property), px, py, 12, 12, null); px += 13; } } } } // draw attached objects int startX = 3; int startY = CardFactory.cardHeight - 18; if (card.registerModifiers != null) { for (int i = card.registerModifiers.length; i-- > 0;) { if (card.registerModifiers[i] != null) { startX = card.registerModifiers[i].paintObject(g, startX, startY); } } } if (card.propertyModifier != null) { startX = card.propertyModifier.paintObject(g, startX, startY); } if (card.idCardModifier != null) { card.idCardModifier.paintObject(g, startX, startY); /* * END drawing additional pictures */ } // Draw the target Id if helper said it final String id = TargetHelper.getInstance().getMyId(card); if (id != null) { if (px + 13 > maxX) { px = 3; py += 13; } if (id == TargetHelper.STR_CONTEXT1) { // TODO I am in the context 1, draw a picture g2D.setColor(Color.BLUE); g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length())); g2D.drawString(id, 5, CardFactory.cardHeight - 15); } else if (id == TargetHelper.STR_CONTEXT2) { // TODO I am in the context 2, draw a picture g2D.setColor(Color.BLUE); g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length())); g2D.drawString(id, 5, CardFactory.cardHeight - 15); } else if (id != TargetHelper.STR_SOURCE) { // } else if (id == TargetHelper.STR_SOURCE) { // TODO I am the source, draw a picture // } else { // I am a target g2D.drawImage(TargetHelper.getInstance().getTargetPictureSml(), px, py, null); py += 12; } } g2D.dispose(); }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintBranchLength(final Graphics2D g, final PhylogenyNode node, final boolean to_pdf, final boolean to_graphics_file) { g.setFont(getTreeFontSet().getSmallFont()); if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK);/*from w ww . ja va 2 s .c om*/ } else { g.setColor(getTreeColorSet().getBranchLengthColor()); } if (!node.isRoot()) { if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) { TreePanel.drawString(FORMATTER_BRANCH_LENGTH.format(node.getDistanceToParent()), node.getParent().getXcoord() + EURO_D, node.getYcoord() - getTreeFontSet()._small_max_descent, g); } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) { TreePanel.drawString(FORMATTER_BRANCH_LENGTH.format(node.getDistanceToParent()), node.getParent().getXcoord() + ROUNDED_D, node.getYcoord() - getTreeFontSet()._small_max_descent, g); } else { TreePanel.drawString(FORMATTER_BRANCH_LENGTH.format(node.getDistanceToParent()), node.getParent().getXcoord() + 3, node.getYcoord() - getTreeFontSet()._small_max_descent, g); } } else { TreePanel.drawString(FORMATTER_BRANCH_LENGTH.format(node.getDistanceToParent()), 3, node.getYcoord() - getTreeFontSet()._small_max_descent, g); } }
From source file:org.forester.archaeopteryx.TreePanel.java
final private int paintTaxonomy(final Graphics2D g, final PhylogenyNode node, final boolean is_in_found_nodes, final boolean to_pdf, final boolean to_graphics_file) { final Taxonomy taxonomy = node.getNodeData().getTaxonomy(); g.setFont(getTreeFontSet().getLargeItalicFont()); if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK);/*from w w w. j a v a2 s.com*/ } else if (is_in_found_nodes) { g.setFont(getTreeFontSet().getLargeItalicFont().deriveFont(TreeFontSet.BOLD_AND_ITALIC)); g.setColor(getTreeColorSet().getFoundColor()); } else if (getControlPanel().isColorAccordingToTaxonomy()) { g.setColor(getTaxonomyBasedColor(node)); } else { g.setColor(getTreeColorSet().getTaxonomyColor()); } final double start_x = node.getXcoord() + 3 + TreePanel.HALF_BOX_SIZE; final double start_y = node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / (node.getNumberOfDescendants() == 1 ? 1 : 3.0)); _sb.setLength(0); if (_control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty(taxonomy.getTaxonomyCode())) { _sb.append(taxonomy.getTaxonomyCode()); _sb.append(" "); } if (_control_panel.isShowTaxonomyNames()) { if (!ForesterUtil.isEmpty(taxonomy.getScientificName()) && !ForesterUtil.isEmpty(taxonomy.getCommonName())) { _sb.append(taxonomy.getScientificName()); _sb.append(" ("); _sb.append(taxonomy.getCommonName()); _sb.append(") "); } else if (!ForesterUtil.isEmpty(taxonomy.getScientificName())) { _sb.append(taxonomy.getScientificName()); _sb.append(" "); } else if (!ForesterUtil.isEmpty(taxonomy.getCommonName())) { _sb.append(taxonomy.getCommonName()); _sb.append(" "); } } final String label = _sb.toString(); /* GUILHEM_BEG */ if ((label.length() > 0) && (node.getNodeData().isHasSequence()) && node.getNodeData().getSequence().equals(_query_sequence)) { // invert font color and background color to show that this is the query sequence final Rectangle2D nodeTextBounds = new TextLayout(label, g.getFont(), new FontRenderContext(null, false, false)).getBounds(); g.fillRect((int) start_x - 1, (int) start_y - 8, (int) nodeTextBounds.getWidth() + 4, 11); g.setColor(getTreeColorSet().getBackgroundColor()); } /* GUILHEM_END */ TreePanel.drawString(label, start_x, start_y, g); if (is_in_found_nodes) { return getTreeFontSet()._fm_large_italic_bold.stringWidth(label); } else { return getTreeFontSet()._fm_large_italic.stringWidth(label); } }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintGainedAndLostCharacters(final Graphics2D g, final PhylogenyNode node, final String gained, final String lost) { if (node.getParent() != null) { final double parent_x = node.getParent().getXcoord(); final double x = node.getXcoord(); g.setFont(getTreeFontSet().getLargeFont()); g.setColor(getTreeColorSet().getGainedCharactersColor()); if (Constants.SPECIAL_CUSTOM) { g.setColor(Color.BLUE); }/*from w w w .j a v a 2 s . c o m*/ TreePanel.drawString(gained, parent_x + ((x - parent_x - getTreeFontSet()._fm_large.stringWidth(gained)) / 2), (node.getYcoord() - getTreeFontSet()._fm_large.getMaxDescent()) - 1, g); g.setColor(getTreeColorSet().getLostCharactersColor()); TreePanel.drawString(lost, parent_x + ((x - parent_x - getTreeFontSet()._fm_large.stringWidth(lost)) / 2), (node.getYcoord() + getTreeFontSet()._fm_large.getMaxAscent()) + 1, g); } }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void paintScale(final Graphics2D g, int x1, int y1, final boolean to_pdf, final boolean to_graphics_file) { if (!getControlPanel().isDrawPhylogram() || (getScaleDistance() <= 0.0)) { return;//ww w .j a va 2s .co m } x1 += MOVE; final double x2 = x1 + (getScaleDistance() * getXcorrectionFactor()); y1 -= 12; final int y2 = y1 - 8; final int y3 = y1 - 4; g.setFont(getTreeFontSet().getSmallFont()); if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) { g.setColor(Color.BLACK); } else { g.setColor(getTreeColorSet().getBranchLengthColor()); } drawLine(x1, y1, x1, y2, g); drawLine(x2, y1, x2, y2, g); drawLine(x1, y3, x2, y3, g); if (getScaleLabel() != null) { g.drawString(getScaleLabel(), (x1 + 2), y3 - 2); } }
From source file:ucar.unidata.idv.ui.ImageGenerator.java
/** * Process the lat/lon labels tag/*from ww w.jav a 2 s . c o m*/ * * @param child the XML * @param viewManager the associated view manager * @param image the image to draw on * @param imageProps the image properties * * @return a new image * * @throws Exception on badness */ public BufferedImage doLatLonLabels(Element child, ViewManager viewManager, BufferedImage image, Hashtable imageProps) throws Exception { if (viewManager == null) { throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a view"); } if (!(viewManager instanceof MapViewManager)) { throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a map view"); } MapViewManager mvm = (MapViewManager) viewManager; NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster(); DecimalFormat format = new DecimalFormat(applyMacros(child, ATTR_FORMAT, "##0.0")); Color color = applyMacros(child, ATTR_COLOR, Color.red); Color lineColor = applyMacros(child, ATTR_LINECOLOR, color); Color bg = applyMacros(child, ATTR_LABELBACKGROUND, (Color) null); double[] latValues = Misc.parseDoubles(applyMacros(child, ATTR_LAT_VALUES, "")); List<String> latLabels = StringUtil.split(applyMacros(child, ATTR_LAT_LABELS, ""), ",", true, true); double[] lonValues = Misc.parseDoubles(applyMacros(child, ATTR_LON_VALUES, "")); List<String> lonLabels = StringUtil.split(applyMacros(child, ATTR_LON_LABELS, ""), ",", true, true); boolean drawLonLines = applyMacros(child, ATTR_DRAWLONLINES, false); boolean drawLatLines = applyMacros(child, ATTR_DRAWLATLINES, false); boolean showTop = applyMacros(child, ATTR_SHOWTOP, false); boolean showBottom = applyMacros(child, ATTR_SHOWBOTTOM, true); boolean showLeft = applyMacros(child, ATTR_SHOWLEFT, true); boolean showRight = applyMacros(child, ATTR_SHOWRIGHT, false); int width = image.getWidth(null); int height = image.getHeight(null); int centerX = width / 2; int centerY = height / 2; EarthLocation nw, ne, se, sw; //don: this what I added Double north = (Double) imageProps.get(ATTR_NORTH); Double south = (Double) imageProps.get(ATTR_SOUTH); Double east = (Double) imageProps.get(ATTR_EAST); Double west = (Double) imageProps.get(ATTR_WEST); //Assume if we have one we have them all if (north != null) { nw = DisplayControlImpl.makeEarthLocation(north.doubleValue(), west.doubleValue(), 0); ne = DisplayControlImpl.makeEarthLocation(north.doubleValue(), east.doubleValue(), 0); sw = DisplayControlImpl.makeEarthLocation(south.doubleValue(), west.doubleValue(), 0); se = DisplayControlImpl.makeEarthLocation(south.doubleValue(), east.doubleValue(), 0); } else { nw = display.screenToEarthLocation(0, 0); ne = display.screenToEarthLocation(width, 0); se = display.screenToEarthLocation(0, height); sw = display.screenToEarthLocation(width, height); } double widthDegrees = ne.getLongitude().getValue() - nw.getLongitude().getValue(); double heightDegrees = ne.getLatitude().getValue() - se.getLatitude().getValue(); Insets insets = getInsets(child, 0); int delta = 2; int bgPad = 1; image = doMatte(image, child, 0); Graphics2D g = (Graphics2D) image.getGraphics(); g.setFont(getFont(child)); FontMetrics fm = g.getFontMetrics(); int lineOffsetRight = applyMacros(child, ATTR_LINEOFFSET_RIGHT, 0); int lineOffsetLeft = applyMacros(child, ATTR_LINEOFFSET_LEFT, 0); int lineOffsetTop = applyMacros(child, ATTR_LINEOFFSET_TOP, 0); int lineOffsetBottom = applyMacros(child, ATTR_LINEOFFSET_BOTTOM, 0); Stroke lineStroke; if (XmlUtil.hasAttribute(child, ATTR_DASHES)) { lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, Misc.parseFloats(applyMacros(child, ATTR_DASHES, "8")), 0.0f); } else { lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0)); } g.setStroke(lineStroke); double leftLon = nw.getLongitude().getValue(CommonUnit.degree); double rightLon = ne.getLongitude().getValue(CommonUnit.degree); Range lonRange = new Range(leftLon, rightLon); for (int i = 0; i < lonValues.length; i++) { double lon = GeoUtils.normalizeLongitude(lonRange, lonValues[i]); double percent = (lon - nw.getLongitude().getValue()) / widthDegrees; // if(percent<0 || percent>1) continue; String label; if (i < lonLabels.size()) { label = lonLabels.get(i); } else { label = format.format(lonValues[i]); } Rectangle2D rect = fm.getStringBounds(label, g); int baseX = insets.left + (int) (percent * width); int x = baseX - (int) rect.getWidth() / 2; int topY; if (insets.top == 0) { topY = (int) rect.getHeight() + delta; } else { topY = insets.top - delta; } if (drawLonLines) { g.setColor(lineColor); g.drawLine(baseX, insets.top + lineOffsetTop, baseX, insets.top + height - lineOffsetBottom); } if (showTop) { if (bg != null) { g.setColor(bg); g.fillRect(x - bgPad, topY - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, x, topY); } int bottomY; if (insets.bottom == 0) { bottomY = insets.top + height - delta; } else { bottomY = insets.top + height + (int) rect.getHeight() + delta; } if (showBottom) { if (bg != null) { g.setColor(bg); g.fillRect(x - bgPad, bottomY - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, x, bottomY); } } for (int i = 0; i < latValues.length; i++) { double lat = latValues[i]; double percent = 1.0 - (lat - se.getLatitude().getValue()) / heightDegrees; int baseY = insets.top + (int) (percent * height); // if(percent<0 || percent>1) continue; String label; if (i < latLabels.size()) { label = latLabels.get(i); } else { label = format.format(lat); } Rectangle2D rect = fm.getStringBounds(label, g); int y = baseY + (int) rect.getHeight() / 2; int leftX; if (insets.left == 0) { leftX = 0 + delta; } else { leftX = insets.left - (int) rect.getWidth() - delta; } if (drawLonLines) { g.setColor(lineColor); g.drawLine(insets.left + lineOffsetRight, baseY, insets.left + width - lineOffsetRight, baseY); } if (showLeft) { if (bg != null) { g.setColor(bg); g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, leftX, y); } if (insets.right == 0) { leftX = insets.left + width - (int) rect.getWidth() - delta; } else { leftX = insets.left + width + delta; } if (showRight) { if (bg != null) { g.setColor(bg); g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, leftX, y); } } return image; }