List of usage examples for java.awt Graphics2D setRenderingHint
public abstract void setRenderingHint(Key hintKey, Object hintValue);
From source file:components.SizeDisplayer.java
protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); //copy g Dimension minSize = getMinimumSize(); Dimension prefSize = getPreferredSize(); Dimension size = getSize();//from w w w . j a va 2 s .c om int prefX = 0, prefY = 0; //Set hints so text looks nice. g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); //Draw the maximum size rectangle if we're opaque. if (isOpaque()) { g2d.setColor(getBackground()); g2d.fillRect(0, 0, size.width, size.height); } //Draw the icon. if (icon != null) { Composite oldComposite = g2d.getComposite(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); icon.paintIcon(this, g2d, (size.width - icon.getIconWidth()) / 2, (size.height - icon.getIconHeight()) / 2); g2d.setComposite(oldComposite); } //Draw the preferred size rectangle. prefX = (size.width - prefSize.width) / 2; prefY = (size.height - prefSize.height) / 2; g2d.setColor(Color.RED); g2d.drawRect(prefX, prefY, prefSize.width - 1, prefSize.height - 1); //Draw the minimum size rectangle. if (minSize.width != prefSize.width || minSize.height != prefSize.height) { int minX = (size.width - minSize.width) / 2; int minY = (size.height - minSize.height) / 2; g2d.setColor(Color.CYAN); g2d.drawRect(minX, minY, minSize.width - 1, minSize.height - 1); } //Draw the text. if (text != null) { Dimension textSize = getTextSize(g2d); g2d.setColor(getForeground()); g2d.drawString(text, (size.width - textSize.width) / 2, (size.height - textSize.height) / 2 + g2d.getFontMetrics().getAscent()); } g2d.dispose(); }
From source file:org.wikipathways.bots.utils.GenerateRSSM.java
private void addThumb(Element biosystem, Pathway p) throws IOException { VPathway vPathway = new VPathway(null); vPathway.fromModel(p);//from ww w. j a va 2 s.c o m double vh = vPathway.getVHeight(); double vw = vPathway.getVWidth(); double zoom = 100; if (vh >= vw) zoom = (double) imgSize / vPathway.getVHeight(); if (vw > vh) zoom = (double) imgSize / vPathway.getVWidth(); vPathway.setPctZoom(zoom * 100); BufferedImage imgThumb = new BufferedImage(vPathway.getVWidth(), vPathway.getVHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = imgThumb.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); vPathway.draw(g); g.dispose(); ByteArrayOutputStream o = new ByteArrayOutputStream(); ImageIO.write(imgThumb, "png", o); o.flush(); byte[] thumbByte = o.toByteArray(); o.close(); byte[] base64enc = Base64.encodeBase64(thumbByte); Element thumb = new Element("thumbnail"); biosystem.addContent(thumb); Element image = new Element("image"); thumb.addContent(image); Element type = new Element("type"); type.addContent(new Element("png")); image.addContent(type); Element enc = new Element("encodedimage"); enc.setText(new String(base64enc)); image.addContent(enc); }
From source file:com.fluidops.iwb.deepzoom.ImageLoader.java
private void generateIDCard(URI uri, Map<URI, Set<Value>> facets, String url, File file) { int width = 200; int height = 200; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D ig2 = bi.createGraphics(); ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ig2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); /* Special ID card handling for certain entity types */ /* TODO: special images based on type if(facets.containsKey(RDF.TYPE)) {/* w ww.j a va2s . c o m*/ Set<Value> facet = facets.get(RDF.TYPE); for(Value v : facet) { if(v.equals(Vocabulary.DCAT_DATASET)) { Image img = null; try { img = ImageIO.read( new File( "webapps/ROOT/images/rdf.jpg" ) ); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error("Could not get image"); } ig2.drawImage( img, 0, 0, null ); break; } } } */ String label = EndpointImpl.api().getDataManager().getLabel(uri); Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20); ig2.setFont(font); FontMetrics fontMetrics = ig2.getFontMetrics(); int labelwidth = fontMetrics.stringWidth(label); if (labelwidth >= width) { int fontsize = 20 * width / labelwidth; font = new Font(Font.SANS_SERIF, Font.BOLD, fontsize); ig2.setFont(font); fontMetrics = ig2.getFontMetrics(); } int x = (width - fontMetrics.stringWidth(label)) / 2; int y = (fontMetrics.getAscent() + (height - (fontMetrics.getAscent() + fontMetrics.getDescent())) / 2); ig2.setPaint(Color.black); ig2.drawString(label, x, y); BufferedOutputStream out; try { out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(bi, "PNG", out); out.flush(); out.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:org.evors.rs.ui.sandpit.TrialViewer.java
@Override public void draw() { if (buffer == null) { return;/*from w w w .j a va 2s . c o m*/ } Graphics2D g2 = (Graphics2D) buffer.getDrawGraphics(); camera.setWindowSize(new Vector2D(this.getWidth(), this.getHeight())); g2.setColor(Color.WHITE); g2.fillRect(0, 0, getWidth(), getHeight()); AffineTransform prevTrans = g2.getTransform(); g2.setTransform(camera.getTransform()); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); grid.draw(g2); if (world != null) { SandpitRenderer.drawWorld(g2, world); } if (path != null) { path.draw(g2); } if (robot != null) { SandpitRenderer.drawRobot(g2, robot); } g2.setTransform(prevTrans); drawText(g2, String.format("Time: %.2f\nRobot position: {%.2f,%.2f}\nRobot heading: %.2f\nInputs:%s\nNeurons:%s", time, robot.getPosition().getX(), robot.getPosition().getY(), robot.getHeading(), Arrays.toString(robot.getInput()), Arrays.toString(((CTRNN) controller.getController()).getNeurons()))); }
From source file:juicebox.mapcolorui.HeatmapRenderer.java
public boolean render(int originX, int originY, int width, int height, final MatrixZoomData zd, final MatrixZoomData controlZD, final MatrixType displayOption, final NormalizationType normalizationType, final ExpectedValueFunction df, Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); int chr1 = zd.getChr1Idx(); int chr2 = zd.getChr2Idx(); int x = originX; int y = originY; boolean isWholeGenome = chr1 == 0 && chr2 == 0; boolean sameChr = (chr1 == chr2); if (sameChr) { // Data is transposable, transpose if necessary. Convention is to use lower diagonal if (x > y) { //noinspection SuspiciousNameCombination x = originY;//from w ww.j av a2s . c om y = originX; int tmp = width; width = height; height = tmp; } } int maxX = x + width - 1; int maxY = y + height - 1; if (displayOption == MatrixType.PEARSON) { BasicMatrix bm = zd.getPearsons(df); ((HiCColorScale) pearsonColorScale).setMin(bm.getLowerValue()); ((HiCColorScale) pearsonColorScale).setMax(bm.getUpperValue()); renderMatrix(bm, originX, originY, width, height, pearsonColorScale, g); } else { // Iterate through blocks overlapping visible region List<Block> blocks = zd.getNormalizedBlocksOverlapping(x, y, maxX, maxY, normalizationType); if (blocks == null) { return false; } boolean hasControl = controlZD != null && (displayOption == MatrixType.CONTROL || displayOption == MatrixType.RATIO); Map<Integer, Block> controlBlocks = new HashMap<Integer, Block>(); if (hasControl) { List<Block> ctrls = controlZD.getNormalizedBlocksOverlapping(x, y, maxX, maxY, normalizationType); for (Block b : ctrls) { controlBlocks.put(b.getNumber(), b); } } String key = zd.getKey() + displayOption; ColorScale cs = getColorScale(key, displayOption, isWholeGenome, blocks); double averageCount = zd.getAverageCount(); // Will get overwritten for intra-chr double ctrlAverageCount = controlZD == null ? 1 : controlZD.getAverageCount(); for (Block b : blocks) { Collection<ContactRecord> recs = b.getContactRecords(); if (recs != null) { Map<String, ContactRecord> controlRecords = new HashMap<String, ContactRecord>(); if (hasControl) { Block cb = controlBlocks.get(b.getNumber()); if (cb != null) { for (ContactRecord ctrlRec : cb.getContactRecords()) { controlRecords.put(ctrlRec.getKey(), ctrlRec); } } } for (ContactRecord rec : recs) { double score = Double.NaN; if (displayOption == MatrixType.OE || displayOption == MatrixType.EXPECTED) { double expected = 0; if (chr1 == chr2) { if (df != null) { int binX = rec.getBinX(); int binY = rec.getBinY(); int dist = Math.abs(binX - binY); expected = df.getExpectedValue(chr1, dist); } } else { expected = (averageCount > 0 ? averageCount : 1); } if (displayOption == MatrixType.OE) { score = rec.getCounts() / expected; } else { score = expected; } } else if (displayOption == MatrixType.CONTROL && hasControl) { ContactRecord ctrlRecord = controlRecords.get(rec.getKey()); if (ctrlRecord != null) score = ctrlRecord.getCounts(); } else if (displayOption == MatrixType.RATIO && hasControl) { ContactRecord ctrlRecord = controlRecords.get(rec.getKey()); if (ctrlRecord != null && ctrlRecord.getCounts() > 0) { double num = rec.getCounts() / averageCount; double den = ctrlRecord.getCounts() / ctrlAverageCount; score = num / den; } } else { score = rec.getCounts(); } if (Double.isNaN(score)) continue; Color color = cs.getColor((float) score); g.setColor(color); int px = rec.getBinX() - originX; int py = rec.getBinY() - originY; if (px > -1 && py > -1 && px <= width && py <= height) { g.fillRect(px, py, HiCGlobals.BIN_PIXEL_WIDTH, HiCGlobals.BIN_PIXEL_WIDTH); } if (sameChr && (rec.getBinX() != rec.getBinY())) { px = (rec.getBinY() - originX); py = (rec.getBinX() - originY); if (px > -1 && py > -1 && px <= width && py <= height) { g.fillRect(px, py, HiCGlobals.BIN_PIXEL_WIDTH, HiCGlobals.BIN_PIXEL_WIDTH); } } } } } } return true; }
From source file:org.eclipse.titanium.graph.visualization.GraphHandler.java
/** * Exports the graph set for this class to a PNG file * /*from ww w .j a v a2 s.com*/ * @param path * : The PNG file's path * @param mode * : The way of export, see {@link GraphHandler} * <code>public static</code> fields for possible values (EXPORT_ * named fields) * @param size * : This parameter sets the size of the exported image in pixels * @throws Exception * on file handling error */ public void saveToImage(final String path, final ImageExportType mode) throws BadLayoutException { if (layout == null || actVisualisator == null) { throw new BadLayoutException("Either the layout or the visuaizer is not set (is null)", ErrorType.NO_OBJECT); } VisualizationViewer<NodeDescriptor, EdgeDescriptor> tempVisualisator = null; Dimension size = null; switch (mode) { case EXPORT_SEEN_GRAPH: { tempVisualisator = actVisualisator; size = actVisualisator.getPreferredSize(); } break; case EXPORT_WHOLE_GRAPH: { layout = actVisualisator.getGraphLayout(); if (size == null) { size = new Dimension(layout.getSize().width, layout.getSize().height); } final Transformer<NodeDescriptor, Point2D> trf = new Transformer<NodeDescriptor, Point2D>() { @Override public Point2D transform(final NodeDescriptor v) { return layout.transform(v); } }; tempVisualisator = new VisualizationViewer<NodeDescriptor, EdgeDescriptor>( new LayoutBuilder(g, Layouts.LAYOUT_STATIC, size).transformer(trf).build()); tempVisualisator.setPreferredSize(size); tempVisualisator.setSize(size); tempVisualisator.getRenderContext().setVertexLabelTransformer(NODE_LABELER); final GraphRenderer<NodeDescriptor, EdgeDescriptor> rnd = new GraphRenderer<NodeDescriptor, EdgeDescriptor>( NODE_LABELER, tempVisualisator.getPickedVertexState(), tempVisualisator.getPickedEdgeState()); setNodeRenderer(rnd, tempVisualisator); tempVisualisator.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); tempVisualisator.setBackground(Color.white); tempVisualisator.setDoubleBuffered(false); } break; case EXPORT_SATELLITE: { tempVisualisator = satView; size = tempVisualisator.getSize(); } break; default: ErrorReporter.logError("Unexpected image export type " + mode); return; } BufferedImage image; final GUIErrorHandler errorHandler = new GUIErrorHandler(); try { image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); } catch (OutOfMemoryError e) { final long needed = (long) size.width * (long) size.height * 4; String temp; if (needed < 1024) { temp = needed + " bytes"; } else if (needed < 1024 * 1024) { temp = needed / 1024 + " Kbytes"; } else { temp = needed / 1024 / 1024 + " Mbytes"; } final String errorText = "Could not save an image of " + size.width + "*" + size.height + " size as there was not enough free memory (" + temp + ")"; errorHandler.reportErrorMessage(errorText); ErrorReporter.logExceptionStackTrace(errorText, e); return; } final Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); tempVisualisator.paint(g2); g2.dispose(); try { ImageIO.write(image, "png", new File(path)); } catch (IOException e) { final String message = "Error while writing to file" + path; ErrorReporter.logExceptionStackTrace(message, e); errorHandler.reportException(message, e); } }
From source file:uk.co.modularaudio.service.gui.impl.racktable.back.AbstractLinkImage.java
private void drawLinkWireIntoImage(final Point sourcePoint, final Point sinkPoint) { // log.debug("Drawing link from " + sourcePoint + " to " + sinkPoint); final int fromX = sourcePoint.x; final int fromY = sourcePoint.y; final int toX = sinkPoint.x; final int toY = sinkPoint.y; float f1, f2, f3, f4, f5, f6, f7, f8 = 0.0f; f1 = fromX;// ww w . ja v a 2s . co m f2 = fromY; f3 = fromX; f4 = fromY + WIRE_DIP_PIXELS; f5 = toX; f6 = toY + WIRE_DIP_PIXELS; f7 = toX; f8 = toY; final CubicCurve2D cubicCurve = new CubicCurve2D.Float(f1, f2, f3, f4, f5, f6, f7, f8); final Rectangle cubicCurveBounds = cubicCurve.getBounds(); final int imageWidthToUse = cubicCurveBounds.width + LINK_IMAGE_PADDING_FOR_WIRE_RADIUS; // int imageHeightToUse = cubicCurveBounds.height + WIRE_DIP_PIXELS; int imageHeightToUse = cubicCurveBounds.height; // If the wire is close to vertical (little Y difference) we make the image a little bigger to account for the wire "dip" if (Math.abs(sinkPoint.y - sourcePoint.y) <= WIRE_DIP_PIXELS) { imageHeightToUse += (WIRE_DIP_PIXELS / 2); } // bufferedImage = new BufferedImage( imageWidthToUse, imageHeightToUse, BufferedImage.TYPE_INT_ARGB ); try { tiledBufferedImage = bufferImageAllocationService.allocateBufferedImage(allocationSource, allocationMatchToUse, AllocationLifetime.SHORT, AllocationBufferType.TYPE_INT_ARGB, imageWidthToUse, imageHeightToUse); bufferedImage = tiledBufferedImage.getUnderlyingBufferedImage(); final Graphics2D g2d = bufferedImage.createGraphics(); g2d.setComposite(AlphaComposite.Clear); g2d.fillRect(0, 0, imageWidthToUse, imageHeightToUse); g2d.setComposite(AlphaComposite.SrcOver); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); f1 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.x; f2 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.y; f3 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.x; f4 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.y; f5 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.x; f6 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.y; f7 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.x; f8 += LINK_IMAGE_DIST_TO_CENTER - cubicCurveBounds.y; final CubicCurve2D offSetCubicCurve = new CubicCurve2D.Float(f1, f2, f3, f4, f5, f6, f7, f8); // Draw the highlight and shadow if (DRAW_HIGHTLIGHT_AND_SHADOW) { final Graphics2D sG2d = (Graphics2D) g2d.create(); sG2d.translate(WIRE_SHADOW_X_OFFSET, WIRE_SHADOW_Y_OFFSET); sG2d.setColor(Color.BLUE.darker()); sG2d.setStroke(new BasicStroke(WIRE_SHADOW_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); sG2d.draw(offSetCubicCurve); final Graphics2D hG2d = (Graphics2D) g2d.create(); hG2d.translate(WIRE_HIGHLIGHT_X_OFFSET, WIRE_HIGHLIGHT_Y_OFFSET); hG2d.setColor(Color.WHITE); hG2d.setStroke( new BasicStroke(WIRE_HIGHLIGHT_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); hG2d.draw(offSetCubicCurve); } g2d.setColor(Color.BLACK); g2d.setStroke(wireStroke); g2d.draw(offSetCubicCurve); g2d.setColor(Color.BLUE); g2d.setStroke(wireBodyStroke); g2d.draw(offSetCubicCurve); // For debugging, draw a green line around the outside of this image. if (DRAW_WIRE_BOUNDING_BOX) { g2d.setStroke(basicStrokeOfOne); g2d.setColor(Color.GREEN); g2d.drawRect(0, 0, imageWidthToUse - 1, imageHeightToUse - 1); } rectangle.x = cubicCurveBounds.x - LINK_IMAGE_DIST_TO_CENTER; rectangle.y = cubicCurveBounds.y - LINK_IMAGE_DIST_TO_CENTER; rectangle.width = imageWidthToUse; rectangle.height = imageHeightToUse; } catch (final Exception e) { final String msg = "Exception caught allocating buffered image: " + e.toString(); log.error(msg, e); } }
From source file:org.eqaula.glue.faces.MethodPrinter.java
public Method printToDownload(Method method) { try {/*from www . j av a 2s . c om*/ if (Method.Type.SEMAPHORE.equals(method.getMethodType())) { // So, browser is requesting the image. Get ID value from actual request param. BufferedImage bufferedImg = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bufferedImg.createGraphics(); String color = "gray"; //Default color if (!method.getWrappers().isEmpty()) { color = method.getWrappers().get(0).getValue(); } Field field = Class.forName("java.awt.Color").getField(color); g2.setColor((Color) field.get(null)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 32F, 32F); g2.fill(sign1); //g2.drawString(method.getTarget().getCurrentValue().toString(), 0, 10); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(bufferedImg, "png", os); writeStreamedContentToFile(method, new ByteArrayInputStream(os.toByteArray())); } } catch (Exception e) { e.printStackTrace(); } return method; }
From source file:CustomStrokes.java
/** Draw the example */ public void paint(Graphics g1) { Graphics2D g = (Graphics2D) g1; // Get a shape to work with. Here we'll use the letter B Font f = new Font("Serif", Font.BOLD, 200); GlyphVector gv = f.createGlyphVector(g.getFontRenderContext(), "B"); Shape shape = gv.getOutline(); // Set drawing attributes and starting position g.setColor(Color.black);/*from www .j a v a2 s . c o m*/ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.translate(10, 175); // Draw the shape once with each stroke for (int i = 0; i < strokes.length; i++) { g.setStroke(strokes[i]); // set the stroke g.draw(shape); // draw the shape g.translate(140, 0); // move to the right } }
From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel.java
/** * Paints the panel component/* w w w. ja va 2 s.c om*/ * * @param g The Graphics */ @Override protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); DrawGraph(g2, graphEx.GetGraphNodes()); }