Java Code Examples for java.awt.Graphics2D#setFont()

The following examples show how to use java.awt.Graphics2D#setFont() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private float getFillLevel(char c, FontMetrics f) {
	
	BufferedImage img = new BufferedImage(f.charWidth(c), f.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	Graphics2D g = img.createGraphics();

	g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antialiasing ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
	g.setFont(font);
	g.setColor(Color.black);
	g.drawString(c+"", 0, img.getHeight()-f.getDescent());
	
	int[] rgb = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
	int totalOpacity = 0;
	
	for(int color : rgb)
		totalOpacity += ImageTools.getAlpha(color);
	
	return totalOpacity / (float)(rgb.length*255);
}
 
Example 2
public static void main(String[] args) {

        BufferedImage bi =
            new BufferedImage(100, 20, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        Font af[] =
            GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();

        for (Font f : af) {
            System.out.println("Looking at font " + f);
            g2d.setFont(f);
            g2d.getFontMetrics().getWidths();
            g2d.drawString(text, 50, 10);
        }
        g2d.dispose();
    }
 
Example 3
private void setParams( Graphics2D g2 ) {
    g2.setFont( testFont );
    g2.setRenderingHint(KEY_TEXT_ANTIALIASING, antiAliasType);
    g2.setRenderingHint(KEY_FRACTIONALMETRICS, fractionalMetricsType);
    g2.setRenderingHint(KEY_TEXT_LCD_CONTRAST, lcdContrast);
    /* I am preserving a somewhat dubious behaviour of this program.
     * Outline text would be drawn anti-aliased by setting the
     * graphics anti-aliasing hint if the text anti-aliasing hint
     * was set. The dubious element here is that people simply
     * using this program may think this is built-in behaviour
     * but its not - at least not when the app explicitly draws
     * outline text.
     * This becomes more dubious in cases such as "GASP" where the
     * size at which text is AA'ed is not something you can easily
     * calculate, so mimicing that behaviour isn't going to be easy.
     * So I precisely preserve the behaviour : this is done only
     * if the AA value is "ON". Its not applied in the other cases.
     */
    if (antiAliasType == VALUE_TEXT_ANTIALIAS_ON &&
        (drawMethod == TL_OUTLINE || drawMethod == GV_OUTLINE)) {
        g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
    } else {
        g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_OFF);
    }
}
 
Example 4
/**
 * Returns the maximum of the relevant dimension (height or width) of the
 * subcategory labels.
 *
 * @param g2  the graphics device.
 * @param edge  the edge.
 *
 * @return The maximum dimension.
 */
private double getMaxDim(Graphics2D g2, RectangleEdge edge) {
    double result = 0.0;
    g2.setFont(this.subLabelFont);
    FontMetrics fm = g2.getFontMetrics();
    Iterator iterator = this.subCategories.iterator();
    while (iterator.hasNext()) {
        Comparable subcategory = (Comparable) iterator.next();
        String label = subcategory.toString();
        Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
        double dim;
        if (RectangleEdge.isLeftOrRight(edge)) {
            dim = bounds.getWidth();
        }
        else {  // must be top or bottom
            dim = bounds.getHeight();
        }
        result = Math.max(result, dim);
    }
    return result;
}
 
Example 5
/**
 * A utility method that draws a string inside a rectangle.
 *
 * @param g2  the graphics device.
 * @param bounds  the rectangle.
 * @param font  the font.
 * @param text  the text.
 */
private void drawStringInRect(Graphics2D g2, Rectangle2D bounds, Font font,
                              String text) {

    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics(font);
    Rectangle2D r = TextUtilities.getTextBounds(text, g2, fm);
    double x = bounds.getX();
    if (r.getWidth() < bounds.getWidth()) {
        x = x + (bounds.getWidth() - r.getWidth()) / 2;
    }
    LineMetrics metrics = font.getLineMetrics(
        text, g2.getFontRenderContext()
    );
    g2.drawString(
        text, (float) x, (float) (bounds.getMaxY()
            - this.bottomInnerGap - metrics.getDescent())
    );
}
 
Example 6
/**
 * Finds the font that fits into the progress arc. Stores the associated height and width.
 */
private static void initializeFontMeasures() {
	platformSpecificFont = DEFAULT_FONT;
	Graphics2D testGraphics = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB).createGraphics();
	float[] possibleFontSizes = { 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10 };

	for (float size : possibleFontSizes) {
		Font deriveFont = DEFAULT_FONT.deriveFont(size);
		testGraphics.setFont(deriveFont);
		String testString = "54";
		Rectangle2D stringBounds = deriveFont.getStringBounds(testString, testGraphics.getFontRenderContext());

		if (stringBounds.getWidth() <= MAXIMAL_TEXT_WIDTH) {
			platformSpecificFont = deriveFont;
			textWidth = stringBounds.getWidth();
			textHeight = deriveFont.createGlyphVector(testGraphics.getFontRenderContext(), testString).getVisualBounds()
					.getHeight();
			break;
		}

	}
}
 
Example 7
Source Project: pumpernickel   File: AbstractTransition.java    License: MIT License 5 votes vote down vote up
/**
 * Create an image with the text provided. This is intended to facilitate
 * simple demos of transitions.
 * 
 * @param size
 *            the width and height of this image.
 * @param text
 *            the text to render, probably just 1 or 2 letters will do.
 * @param light
 *            whether to use a light (red/yellow) background or a dark
 *            (green/blue) background.
 * @param useGradients
 *            whether to use gradients as a background or not.
 * @return an image to test transitions with.
 */
public static BufferedImage createImage(int size, String text,
		boolean light, boolean useGradients) {
	BufferedImage bi = new BufferedImage(size, size,
			BufferedImage.TYPE_INT_RGB);
	Font font = new Font("Default", 0, size * 150 / 200);
	FontRenderContext frc = new FontRenderContext(new AffineTransform(),
			true, true);

	Graphics2D g = bi.createGraphics();
	if (useGradients) {
		if (light) {
			g.setPaint(new GradientPaint(0, bi.getHeight(), Color.red, bi
					.getWidth(), 0, Color.yellow, true));
		} else {
			g.setPaint(new GradientPaint(0, 0, Color.blue, bi.getWidth(),
					bi.getHeight(), Color.green, true));
		}
	} else {
		if (light) {
			g.setPaint(new Color(0xE19839));
		} else {
			g.setPaint(new Color(0x3B4E92));
		}
	}
	g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
	g.setColor(Color.black);
	g.setFont(font);
	float width = (float) font.getStringBounds(text, frc).getWidth();
	g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
	g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
			RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	g.drawString(text, bi.getWidth() / 2 - width / 2, size * 160 / 200);
	g.dispose();

	return bi;
}
 
Example 8
private void drawLabel(Rendering rendering, String label) {

        final Graphics2D graphics = rendering.getGraphics();
        final Font oldFont = graphics.getFont();
        final Stroke oldStroke = graphics.getStroke();
        final Paint oldPaint = graphics.getPaint();

        try {
            graphics.setFont(labelFont);
            GlyphVector glyphVector = labelFont.createGlyphVector(graphics.getFontRenderContext(), label);
            Rectangle2D logicalBounds = glyphVector.getLogicalBounds();
            float tx = (float) (logicalBounds.getX() - 0.5 * logicalBounds.getWidth());
            float ty = (float) (getSymbol().getBounds().getMaxY() + logicalBounds.getHeight() + 1.0);
            Shape labelOutline = glyphVector.getOutline(tx, ty);

            for (int i = 0; i < labelOutlineAlphas.length; i++) {
                graphics.setStroke(labelOutlineStrokes[i]);
                graphics.setPaint(labelOutlineColors[i]);
                graphics.draw(labelOutline);
            }

            graphics.setPaint(labelFontColor);
            graphics.fill(labelOutline);
        } finally {
            graphics.setPaint(oldPaint);
            graphics.setStroke(oldStroke);
            graphics.setFont(oldFont);
        }
    }
 
Example 9
private static void renderTo(BufferedImage dst) {
    System.out.println("The buffer: " + dst);
    Graphics2D g = dst.createGraphics();

    final int w = dst.getWidth();
    final int h = dst.getHeight();

    g.setColor(Color.blue);
    g.fillRect(0, 0, w, h);

    g.setColor(Color.red);
    Font f = g.getFont();
    g.setFont(f.deriveFont(48f));

    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
           RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    // NB: this clip ctriggers the problem
    g.setClip(50, 50, 200, 100);

    g.drawString("AA Text", 52, 90);

    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
           RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

    // NB: this clip ctriggers the problem
    g.setClip(50, 100, 100, 100);
    g.drawString("Text", 52, 148);

    g.dispose();
}
 
Example 10
/**
 * Draws the label for one axis.
 *
 * @param g2  the graphics device.
 * @param plotArea  the plot area
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value,
                         int cat, double startAngle, double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

    String label;
    if (this.dataExtractOrder == TableOrder.BY_ROW) {
        // if series are in rows, then the categories are the column keys
        label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
    }
    else {
        // if series are in columns, then the categories are the row keys
        label = this.labelGenerator.generateRowLabel(this.dataset, cat);
    }

    Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
    LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
    double ascent = lm.getAscent();

    Point2D labelLocation = calculateLabelLocation(labelBounds, ascent,
            plotArea, startAngle);

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
            1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(getLabelFont());
    g2.drawString(label, (float) labelLocation.getX(),
            (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}
 
Example 11
private void render(Image im, int type, String s) {
    Graphics2D g2d = (Graphics2D) im.getGraphics();
    clear(g2d, type, im.getWidth(null), im.getHeight(null));
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
    Font f = new Font("Dialog", Font.BOLD, 40);// g2d.getFont().deriveFont(32.0f);
    g2d.setColor(Color.white);
    g2d.setFont(g2d.getFont().deriveFont(36.0f));
    g2d.drawString(s, 10, im.getHeight(null) / 2);
}
 
Example 12
/**
 * Get graphic rectangle
 *
 * @param g The graphics
 * @param aGraphic The graphic
 * @param area Area
 * @return Rectangle
 */
public Rectangle getGraphicRectangle(Graphics2D g, Graphic aGraphic, Rectangle2D area) {
    Rectangle rect = new Rectangle();
    double[] sXY;
    float aX, aY;
    switch (aGraphic.getShape().getShapeType()) {
        case Point:
        case PointM:
            PointShape aPS = (PointShape) aGraphic.getShape();
            sXY = projToScreen(aPS.getPoint().X, aPS.getPoint().Y, area);
            aX = (float) sXY[0];
            aY = (float) sXY[1];
            switch (aGraphic.getLegend().getBreakType()) {
                case PointBreak:
                    PointBreak aPB = (PointBreak) aGraphic.getLegend();
                    int buffer = (int) aPB.getSize() + 2;
                    rect.x = (int) aX - buffer / 2;
                    rect.y = (int) aY - buffer / 2;
                    rect.width = buffer;
                    rect.height = buffer;
                    break;
                case LabelBreak:
                    LabelBreak aLB = (LabelBreak) aGraphic.getLegend();
                    g.setFont(aLB.getFont());
                    //FontMetrics metrics = g.getFontMetrics(aLB.getFont());
                    //Dimension labSize = new Dimension(metrics.stringWidth(aLB.getText()), metrics.getHeight());
                    Dimension labSize = Draw.getStringDimension(aLB.getText(), g);
                    switch (aLB.getAlignType()) {
                        case Center:
                            aX = aX - labSize.width / 2;
                            break;
                        case Left:
                            aX = aX - labSize.width;
                            break;
                    }
                    aY -= aLB.getYShift();
                    aY -= labSize.height / 3;
                    rect.x = (int) aX;
                    rect.y = (int) aY;
                    rect.width = (int) labSize.width;
                    rect.height = (int) labSize.height;
                    break;
            }
            break;
        case Polyline:
        case Polygon:
        case Rectangle:
        case CurveLine:
        case Ellipse:
        case Circle:
        case CurvePolygon:
            List<PointD> newPList = (List<PointD>) aGraphic.getShape().getPoints();
            List<PointD> points = new ArrayList<>();
            for (PointD wPoint : newPList) {
                sXY = projToScreen(wPoint.X, wPoint.Y, area);
                aX = (float) sXY[0];
                aY = (float) sXY[1];
                points.add(new PointD(aX, aY));
            }
            Extent aExtent = MIMath.getPointsExtent(points);
            rect.x = (int) aExtent.minX;
            rect.y = (int) aExtent.minY;
            rect.width = (int) (aExtent.maxX - aExtent.minX);
            rect.height = (int) (aExtent.maxY - aExtent.minY);
            break;
    }

    return rect;
}
 
Example 13
/**
 * Draws the scale on the dial plot.
 *
 * @param g2  the graphics target (<code>null</code> not permitted).
 * @param plot  the dial plot (<code>null</code> not permitted).
 * @param frame  the reference frame that is used to construct the
 *     geometry of the plot (<code>null</code> not permitted).
 * @param view  the visible part of the plot (<code>null</code> not 
 *     permitted).
 */
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, 
        Rectangle2D view) {
    
    Rectangle2D arcRect = DialPlot.rectangleByRadius(frame, 
            this.tickRadius, this.tickRadius);
    Rectangle2D arcRectMajor = DialPlot.rectangleByRadius(frame, 
            this.tickRadius - this.majorTickLength, 
            this.tickRadius - this.majorTickLength);
    Rectangle2D arcRectMinor = arcRect;
    if (this.minorTickCount > 0 && this.minorTickLength > 0.0) {
        arcRectMinor = DialPlot.rectangleByRadius(frame, 
                this.tickRadius - this.minorTickLength, 
                this.tickRadius - this.minorTickLength);
    }
    Rectangle2D arcRectForLabels = DialPlot.rectangleByRadius(frame, 
            this.tickRadius - this.tickLabelOffset, 
            this.tickRadius - this.tickLabelOffset);
    
    boolean firstLabel = true;
    
    Arc2D arc = new Arc2D.Double();
    Line2D workingLine = new Line2D.Double();
    for (double v = this.lowerBound; v <= this.upperBound; 
            v += this.majorTickIncrement) {
        arc.setArc(arcRect, this.startAngle, valueToAngle(v) 
                - this.startAngle, Arc2D.OPEN);
        Point2D pt0 = arc.getEndPoint();
        arc.setArc(arcRectMajor, this.startAngle, valueToAngle(v) 
                - this.startAngle, Arc2D.OPEN);
        Point2D pt1 = arc.getEndPoint();
        g2.setPaint(this.majorTickPaint);
        g2.setStroke(this.majorTickStroke);
        workingLine.setLine(pt0, pt1);
        g2.draw(workingLine);
        arc.setArc(arcRectForLabels, this.startAngle, valueToAngle(v) 
                - this.startAngle, Arc2D.OPEN);
        Point2D pt2 = arc.getEndPoint();
        
        if (this.tickLabelsVisible) {
            if (!firstLabel || this.firstTickLabelVisible) {
                g2.setFont(this.tickLabelFont);
                TextUtilities.drawAlignedString(
                        this.tickLabelFormatter.format(v), g2, 
                        (float) pt2.getX(), (float) pt2.getY(), 
                        TextAnchor.CENTER);
            }
        }
        firstLabel = false;
        
        // now do the minor tick marks
        if (this.minorTickCount > 0 && this.minorTickLength > 0.0) {
            double minorTickIncrement = this.majorTickIncrement 
                    / (this.minorTickCount + 1);
            for (int i = 0; i < this.minorTickCount; i++) {
                double vv = v + ((i + 1) * minorTickIncrement);
                if (vv >= this.upperBound) {
                    break;
                }
                double angle = valueToAngle(vv);
               
                arc.setArc(arcRect, this.startAngle, angle 
                        - this.startAngle, Arc2D.OPEN);
                pt0 = arc.getEndPoint();
                arc.setArc(arcRectMinor, this.startAngle, angle 
                        - this.startAngle, Arc2D.OPEN);
                Point2D pt3 = arc.getEndPoint();
                g2.setStroke(this.minorTickStroke);
                g2.setPaint(this.minorTickPaint);
                workingLine.setLine(pt0, pt3);
                g2.draw(workingLine);
            }
        }
        
    }
}
 
Example 14
Source Project: coming   File: JGenProg2017_00124_s.java    License: MIT License 4 votes vote down vote up
/**
 * Draws a marker for the domain axis.
 *
 * @param g2  the graphics device (not <code>null</code>).
 * @param plot  the plot (not <code>null</code>).
 * @param axis  the range axis (not <code>null</code>).
 * @param marker  the marker to be drawn (not <code>null</code>).
 * @param dataArea  the area inside the axes (not <code>null</code>).
 *
 * @see #drawRangeMarker(Graphics2D, CategoryPlot, ValueAxis, Marker,
 *     Rectangle2D)
 */
public void drawDomainMarker(Graphics2D g2,
                             CategoryPlot plot,
                             CategoryAxis axis,
                             CategoryMarker marker,
                             Rectangle2D dataArea) {

    Comparable category = marker.getKey();
    CategoryDataset dataset = plot.getDataset(plot.getIndexOf(this));
    int columnIndex = dataset.getColumnIndex(category);
    if (columnIndex < 0) {
        return;
    }

    final Composite savedComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, marker.getAlpha()));

    PlotOrientation orientation = plot.getOrientation();
    Rectangle2D bounds = null;
    if (marker.getDrawAsLine()) {
        double v = axis.getCategoryMiddle(columnIndex,
                dataset.getColumnCount(), dataArea,
                plot.getDomainAxisEdge());
        Line2D line = null;
        if (orientation == PlotOrientation.HORIZONTAL) {
            line = new Line2D.Double(dataArea.getMinX(), v,
                    dataArea.getMaxX(), v);
        }
        else if (orientation == PlotOrientation.VERTICAL) {
            line = new Line2D.Double(v, dataArea.getMinY(), v,
                    dataArea.getMaxY());
        }
        g2.setPaint(marker.getPaint());
        g2.setStroke(marker.getStroke());
        g2.draw(line);
        bounds = line.getBounds2D();
    }
    else {
        double v0 = axis.getCategoryStart(columnIndex,
                dataset.getColumnCount(), dataArea,
                plot.getDomainAxisEdge());
        double v1 = axis.getCategoryEnd(columnIndex,
                dataset.getColumnCount(), dataArea,
                plot.getDomainAxisEdge());
        Rectangle2D area = null;
        if (orientation == PlotOrientation.HORIZONTAL) {
            area = new Rectangle2D.Double(dataArea.getMinX(), v0,
                    dataArea.getWidth(), (v1 - v0));
        }
        else if (orientation == PlotOrientation.VERTICAL) {
            area = new Rectangle2D.Double(v0, dataArea.getMinY(),
                    (v1 - v0), dataArea.getHeight());
        }
        g2.setPaint(marker.getPaint());
        g2.fill(area);
        bounds = area;
    }

    String label = marker.getLabel();
    RectangleAnchor anchor = marker.getLabelAnchor();
    if (label != null) {
        Font labelFont = marker.getLabelFont();
        g2.setFont(labelFont);
        g2.setPaint(marker.getLabelPaint());
        Point2D coordinates = calculateDomainMarkerTextAnchorPoint(
                g2, orientation, dataArea, bounds, marker.getLabelOffset(),
                marker.getLabelOffsetType(), anchor);
        TextUtilities.drawAlignedString(label, g2,
                (float) coordinates.getX(), (float) coordinates.getY(),
                marker.getLabelTextAnchor());
    }
    g2.setComposite(savedComposite);
}
 
Example 15
Source Project: geopackage-java   File: NumberFeaturesTile.java    License: MIT License 4 votes vote down vote up
/**
 * Draw a tile with the provided text label in the middle
 *
 * @param tileWidth
 * @param tileHeight
 * @param text
 * @return
 */
private BufferedImage drawTile(int tileWidth, int tileHeight, String text) {

	// Create the image and graphics
	BufferedImage image = new BufferedImage(tileWidth, tileHeight,
			BufferedImage.TYPE_INT_ARGB);
	Graphics2D graphics = image.createGraphics();
	graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);

	// Draw the tile fill paint
	if (tileFillColor != null) {
		graphics.setColor(tileFillColor);
		graphics.fillRect(0, 0, tileWidth, tileHeight);
	}

	// Draw the tile border
	if (tileBorderColor != null) {
		graphics.setColor(tileBorderColor);
		graphics.setStroke(new BasicStroke(tileBorderStrokeWidth));
		graphics.drawRect(0, 0, tileWidth, tileHeight);
	}

	// Determine the text bounds
	graphics.setFont(new Font(textFont, Font.PLAIN, textSize));
	FontMetrics fontMetrics = graphics.getFontMetrics();
	int textWidth = fontMetrics.stringWidth(text);
	int textHeight = fontMetrics.getAscent();

	// Determine the center of the tile
	int centerX = (int) (image.getWidth() / 2.0f);
	int centerY = (int) (image.getHeight() / 2.0f);

	// Draw the circle
	if (circleColor != null || circleFillColor != null) {
		int diameter = Math.max(textWidth, textHeight);
		float radius = diameter / 2.0f;
		radius = radius + (diameter * circlePaddingPercentage);
		int paddedDiameter = Math.round(radius * 2);

		int circleX = Math.round(centerX - radius);
		int circleY = Math.round(centerY - radius);

		// Draw the filled circle
		if (circleFillColor != null) {
			graphics.setColor(circleFillColor);
			graphics.setStroke(new BasicStroke(circleStrokeWidth));
			graphics.fillOval(circleX, circleY, paddedDiameter,
					paddedDiameter);
		}

		// Draw the circle
		if (circleColor != null) {
			graphics.setColor(circleColor);
			graphics.setStroke(new BasicStroke(circleStrokeWidth));
			graphics.drawOval(circleX, circleY, paddedDiameter,
					paddedDiameter);
		}

	}

	// Draw the text
	float textX = centerX - (textWidth / 2.0f);
	float textY = centerY + (textHeight / 2.0f);
	graphics.setColor(textColor);
	graphics.drawString(text, textX, textY);

	return image;
}
 
Example 16
Source Project: smart-framework   File: WebUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 创建验证码
 */
public static String createCaptcha(HttpServletResponse response) {
    StringBuilder captcha = new StringBuilder();
    try {
        // 参数初始化
        int width = 60;                      // 验证码图片的宽度
        int height = 31;                     // 验证码图片的高度
        int codeCount = 4;                   // 验证码字符个数
        int codeX = width / (codeCount + 1); // 字符横向间距
        int codeY = height - 4;              // 字符纵向间距
        int fontHeight = height - 2;         // 字体高度
        int randomSeed = 36;                 // 随机数种子
        char[] codeSequence = {              // 验证码中可出现的字符
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E',
            'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',
            'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O',
            'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',
            'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y',
            'z', 'Z'
        };
        // 创建图像
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 设置字体
        g.setFont(new Font("Courier New", Font.BOLD, fontHeight));
        // 绘制边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 产生随机干扰线(160条)
        g.setColor(Color.WHITE);
        // 创建随机数生成器
        Random random = new Random();
        for (int i = 0; i < 160; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        // 生成随机验证码
        int red, green, blue;
        for (int i = 0; i < codeCount; i++) {
            // 获取随机验证码
            String validateCode = String.valueOf(codeSequence[random.nextInt(randomSeed)]);
            // 随机构造颜色值
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            // 将带有颜色的验证码绘制到图像中
            g.setColor(new Color(red, green, blue));
            g.drawString(validateCode, (i + 1) * codeX - 6, codeY);
            // 将产生的随机数拼接起来
            captcha.append(validateCode);
        }
        // 禁止图像缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置响应类型为 JPEG 图片
        response.setContentType("image/jpeg");
        // 将缓冲图像写到 Servlet 输出流中
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(bi, "jpeg", sos);
        sos.close();
    } catch (Exception e) {
        logger.error("创建验证码出错!", e);
        throw new RuntimeException(e);
    }
    return captcha.toString();
}
 
Example 17
private void paintNodes(Graphics2D g, int height) {
	for (Map.Entry<Integer, List<Node>> entry : layers.entrySet()) {
		int layerIndex = entry.getKey();
		List<Node> layer = entry.getValue();
		int nodes = layer.size();
		if (layerIndex < layers.size() - 1) {
			nodes++;
		}

		String layerName = null;
		if (layerIndex == 0) {
			layerName = "Input";
		} else if (layerIndex == layers.size() - 1) {
			layerName = "Output";
		} else {
			layerName = "Hidden " + layerIndex;
		}

		g.setFont(LAYER_FONT);
		g.setColor(Color.BLACK);
		Rectangle2D stringBounds = g.getFontMetrics().getStringBounds(layerName, g);
		g.drawString(layerName, (int) (-1 * stringBounds.getWidth() / 2 + NODE_RADIUS / 2), 0);
		int yPos = height / 2 - nodes * ROW_HEIGHT / 2;
		for (int r = 0; r < nodes; r++) {
			Shape node = new Ellipse2D.Double(0, yPos, NODE_RADIUS, NODE_RADIUS);
			if (layerIndex == 0 || layerIndex == layers.size() - 1) {
				if (r < nodes - 1 || layerIndex == layers.size() - 1) {
					g.setPaint(SwingTools.makeYellowPaint(NODE_RADIUS, NODE_RADIUS));
				} else {
					g.setPaint(NODE_ALMOST_WHITE);
				}
			} else {
				if (r < nodes - 1) {
					g.setPaint(SwingTools.makeBluePaint(NODE_RADIUS, NODE_RADIUS));
				} else {
					g.setPaint(NODE_ALMOST_WHITE);
				}
			}
			g.fill(node);
			if (layerIndex == this.selectedLayerIndex && r == this.selectedRowIndex) {
				g.setColor(Color.RED);
			} else {
				g.setColor(Color.BLACK);
			}
			g.draw(node);
			yPos += ROW_HEIGHT;
		}
		g.translate(LAYER_WIDTH, 0);
		layerIndex++;
	}
}
 
Example 18
protected void paintBase(InstancePainter painter, boolean drawname, boolean ghost) {
	Direction dir = painter.getAttributeValue(StdAttr.FACING);
	Graphics2D g = (Graphics2D) painter.getGraphics();
	Bounds bds = painter.getBounds();
	int x = bds.getX();
	int y = bds.getY();
	int xp = x, yp = y;
	int width = bds.getWidth();
	int height = bds.getHeight();
	for (byte i = 0; i < this.pinnumber; i++) {
		if (i < this.pinnumber / 2) {
			if (dir == Direction.WEST || dir == Direction.EAST)
				xp = i * 20 + (10 - pinwidth / 2) + x;
			else
				yp = i * 20 + (10 - pinwidth / 2) + y;
		} else {
			if (dir == Direction.WEST || dir == Direction.EAST) {
				xp = (i - this.pinnumber / 2) * 20 + (10 - pinwidth / 2) + x;
				yp = height + y - pinheight;
			} else {
				yp = (i - this.pinnumber / 2) * 20 + (10 - pinwidth / 2) + y;
				xp = width + x - pinheight;
			}
		}
		if (dir == Direction.WEST || dir == Direction.EAST) {
			// fill the background of white if selected from preferences
			if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
				g.setColor(Color.WHITE);
				g.fillRect(xp, yp, pinwidth, pinheight);
				g.setColor(Color.BLACK);
			}
			g.drawRect(xp, yp, pinwidth, pinheight);
		} else {
			// fill the background of white if selected from preferences
			if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
				g.setColor(Color.WHITE);
				g.fillRect(xp, yp, pinheight, pinwidth);
				g.setColor(Color.BLACK);
			}
			g.drawRect(xp, yp, pinheight, pinwidth);
		}
	}
	if (dir == Direction.SOUTH) {
		// fill the background of white if selected from preferences
		if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
			g.setColor(Color.WHITE);
			g.fillRoundRect(x + pinheight, y, bds.getWidth() - pinheight * 2, bds.getHeight(), 10, 10);
			g.setColor(Color.BLACK);
		}
		g.drawRoundRect(x + pinheight, y, bds.getWidth() - pinheight * 2, bds.getHeight(), 10, 10);
		g.drawArc(x + width / 2 - 7, y - 7, 14, 14, 180, 180);
	} else if (dir == Direction.WEST) {
		// fill the background of white if selected from preferences
		if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
			g.setColor(Color.WHITE);
			g.fillRoundRect(x, y + pinheight, bds.getWidth(), bds.getHeight() - pinheight * 2, 10, 10);
			g.setColor(Color.BLACK);
		}
		g.drawRoundRect(x, y + pinheight, bds.getWidth(), bds.getHeight() - pinheight * 2, 10, 10);
		g.drawArc(x + width - 7, y + height / 2 - 7, 14, 14, 90, 180);
	} else if (dir == Direction.NORTH) {
		// fill the background of white if selected from preferences
		if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
			g.setColor(Color.WHITE);
			g.fillRoundRect(x + pinheight, y, bds.getWidth() - pinheight * 2, bds.getHeight(), 10, 10);
			g.setColor(Color.BLACK);
		}
		g.drawRoundRect(x + pinheight, y, bds.getWidth() - pinheight * 2, bds.getHeight(), 10, 10);
		g.drawArc(x + width / 2 - 7, y + height - 7, 14, 14, 0, 180);
	} else {// east
		// fill the background of white if selected from preferences
		if (!ghost && AppPreferences.FILL_COMPONENT_BACKGROUND.getBoolean()) {
			g.setColor(Color.WHITE);
			g.fillRoundRect(x, y + pinheight, bds.getWidth(), bds.getHeight() - pinheight * 2, 10, 10);
			g.setColor(Color.BLACK);
		}
		g.drawRoundRect(x, y + pinheight, bds.getWidth(), bds.getHeight() - pinheight * 2, 10, 10);
		g.drawArc(x - 7, y + height / 2 - 7, 14, 14, 270, 180);
	}
	g.rotate(Math.toRadians(-dir.toDegrees()), x + width / 2, y + height / 2);
	if (drawname) {
		g.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 14));
		GraphicsUtil.drawCenteredText(g, this.name, x + bds.getWidth() / 2, y + bds.getHeight() / 2 - 4);
	}
	if (dir == Direction.WEST || dir == Direction.EAST) {
		xp = x;
		yp = y;
	} else {
		xp = x + (width - height) / 2;
		yp = y + (height - width) / 2;
		width = bds.getHeight();
		height = bds.getWidth();
	}
	g.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 7));
	GraphicsUtil.drawCenteredText(g, "Vcc", xp + 10, yp + pinheight + 4);
	GraphicsUtil.drawCenteredText(g, "GND", xp + width - 10, yp + height - pinheight - 7);
}
 
Example 19
Source Project: astor   File: SymbolAxis.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calculates the positions of the tick labels for the axis, storing the
 * results in the tick label list (ready for drawing).
 *
 * @param g2  the graphics device.
 * @param dataArea  the area in which the data should be drawn.
 * @param edge  the location of the axis.
 *
 * @return The ticks.
 */
protected List refreshTicksHorizontal(Graphics2D g2,
                                      Rectangle2D dataArea,
                                      RectangleEdge edge) {

    List ticks = new java.util.ArrayList();

    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);

    double size = getTickUnit().getSize();
    int count = calculateVisibleTickCount();
    double lowestTickValue = calculateLowestVisibleTickValue();

    double previousDrawnTickLabelPos = 0.0;
    double previousDrawnTickLabelLength = 0.0;

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            double xx = valueToJava2D(currentTickValue, dataArea, edge);
            String tickLabel;
            NumberFormat formatter = getNumberFormatOverride();
            if (formatter != null) {
                tickLabel = formatter.format(currentTickValue);
            }
            else {
                tickLabel = valueToString(currentTickValue);
            }

            // avoid to draw overlapping tick labels
            Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
                    g2.getFontMetrics());
            double tickLabelLength = isVerticalTickLabels()
                    ? bounds.getHeight() : bounds.getWidth();
            boolean tickLabelsOverlapping = false;
            if (i > 0) {
                double avgTickLabelLength = (previousDrawnTickLabelLength
                        + tickLabelLength) / 2.0;
                if (Math.abs(xx - previousDrawnTickLabelPos)
                        < avgTickLabelLength) {
                    tickLabelsOverlapping = true;
                }
            }
            if (tickLabelsOverlapping) {
                tickLabel = ""; // don't draw this tick label
            }
            else {
                // remember these values for next comparison
                previousDrawnTickLabelPos = xx;
                previousDrawnTickLabelLength = tickLabelLength;
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;
            if (isVerticalTickLabels()) {
                anchor = TextAnchor.CENTER_RIGHT;
                rotationAnchor = TextAnchor.CENTER_RIGHT;
                if (edge == RectangleEdge.TOP) {
                    angle = Math.PI / 2.0;
                }
                else {
                    angle = -Math.PI / 2.0;
                }
            }
            else {
                if (edge == RectangleEdge.TOP) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                }
                else {
                    anchor = TextAnchor.TOP_CENTER;
                    rotationAnchor = TextAnchor.TOP_CENTER;
                }
            }
            Tick tick = new NumberTick(new Double(currentTickValue),
                    tickLabel, anchor, rotationAnchor, angle);
            ticks.add(tick);
        }
    }
    return ticks;

}
 
Example 20
/**
 * Presents the Exceptions if the chart cannot be displayed properly.
 * 
 * @param g2d
 * @param ex
 */
private final void showException( Graphics2D g2d, Exception ex )
{
	String sWrappedException = ex.getClass( ).getName( );
	Throwable th = ex;
	while ( ex.getCause( ) != null )
	{
		ex = (Exception) ex.getCause( );
	}
	String sException = ex.getClass( ).getName( );
	if ( sWrappedException.equals( sException ) )
	{
		sWrappedException = null;
	}

	String sMessage = null;
	if ( th instanceof BirtException )
	{
		sMessage = ( (BirtException) th ).getLocalizedMessage( );
	}
	else
	{
		sMessage = ex.getMessage( );
	}

	if ( sMessage == null )
	{
		sMessage = "<null>";//$NON-NLS-1$
	}

	StackTraceElement[] stea = ex.getStackTrace( );
	Dimension d = getSize( );

	Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
	g2d.setFont( fo );
	FontMetrics fm = g2d.getFontMetrics( );
	g2d.setColor( Color.WHITE );
	g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setColor( Color.BLACK );
	g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
	g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
	int x = 25, y = 20 + fm.getHeight( );
	g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.RED );
	g2d.drawString( sException, x, y );
	x = 25;
	y += fm.getHeight( );
	if ( sWrappedException != null )
	{
		g2d.setColor( Color.BLACK );
		g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
		x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
		g2d.setColor( Color.RED );
		g2d.drawString( sWrappedException, x, y );
		x = 25;
		y += fm.getHeight( );
	}
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Message:", x, y );//$NON-NLS-1$
	x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
	g2d.setColor( Color.BLUE );
	g2d.drawString( sMessage, x, y );
	x = 25;
	y += fm.getHeight( );
	g2d.setColor( Color.BLACK );
	y += 10;
	g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
	x = 40;
	y += fm.getHeight( );
	g2d.setColor( Color.GREEN.darker( ) );
	for ( int i = 0; i < stea.length; i++ )
	{
		g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
				+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
				+ stea[i].getLineNumber( ), x, y );
		x = 40;
		y += fm.getHeight( );
	}
}