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

The following examples show how to use java.awt.Graphics2D#drawString() . 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
Source Project: pumpernickel   File: BoxContainerPanelUI.java    License: MIT License 6 votes vote down vote up
protected void paintBox(Graphics2D g, Box box) {
	if (box.getComponent() != null) {
		return;
	}
	Rectangle r = box.getBounds();
	g.setColor(Color.lightGray);
	g.setPaint(new GradientPaint(0, r.y, new Color(0xffffff), 0, r.y
			+ r.height, new Color(0xdddddd)));
	g.fill(r);
	g.setColor(Color.darkGray);
	g.draw(r);

	g.setColor(Color.black);
	String boxName = box.toString();
	Rectangle2D bounds = g.getFont().getStringBounds(boxName,
			g.getFontRenderContext());
	if (bounds.getWidth() + 10 > r.width) {
		r.setBounds(r.x, r.y, (int) (Math.ceil(bounds.getWidth()) + 10.5),
				r.height);
	}
	g.drawString(boxName, r.x + 5, r.y + 15);
}
 
Example 2
Source Project: xxshop   File: VerifyCodeUtil.java    License: Apache License 2.0 6 votes vote down vote up
public BufferedImage getImage () {
	BufferedImage image = createImage(); 
	Graphics2D g2 = (Graphics2D)image.getGraphics();
	StringBuilder sb = new StringBuilder();
	for(int i = 0; i < 4; i++)  {
		String s = randomChar() + ""; 
		sb.append(s); 
		float x = i * 1.0F * w / 4; 
		g2.setFont(randomFont()); 
		g2.setColor(randomColor()); 
		g2.drawString(s, x, h-5); 
	}
	this.text = sb.toString(); 
	drawLine(image); 
	return image;		
}
 
Example 3
Source Project: yGuard   File: YGuardLogParser.java    License: MIT License 6 votes vote down vote up
public void paintIcon(Component c, Graphics g, int x, int y) {
  g.translate(x, y);
  g.setColor(color);
  Graphics2D g2d = (Graphics2D) g;
  Object a = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2d.fill(circle);
  g2d.setColor(color.darker());
  g2d.draw(circle);
  float width = (float) g2d.getFontMetrics().getStringBounds(label, g2d).getWidth();
  g2d.setColor(Color.black);
  g2d.drawString(label, 9 - width * 0.5f, 14);
  g2d.setColor(Color.white);
  g2d.drawString(label, 8 - width * 0.5f, 13);
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, a);
  g.translate(-x, -y);
}
 
Example 4
private static void drawErrorText(@Nonnull final Graphics2D gfx, @Nonnull final Dimension fullSize, @Nonnull final String error) {
  final Font font = new Font(Font.DIALOG, Font.BOLD, 24);
  final FontMetrics metrics = gfx.getFontMetrics(font);
  final Rectangle2D textBounds = metrics.getStringBounds(error, gfx);
  gfx.setFont(font);
  gfx.setColor(Color.DARK_GRAY);
  gfx.fillRect(0, 0, fullSize.width, fullSize.height);
  final int x = (int) (fullSize.width - textBounds.getWidth()) / 2;
  final int y = (int) (fullSize.height - textBounds.getHeight()) / 2;
  gfx.setColor(Color.BLACK);
  gfx.drawString(error, x + 5, y + 5);
  gfx.setColor(Color.RED.brighter());
  gfx.drawString(error, x, y);
}
 
Example 5
private void drawToolTip(Graphics2D g) {
	if (currentToolTip != null) {
		g.setFont(LABEL_FONT);
		Rectangle2D stringBounds = LABEL_FONT.getStringBounds(currentToolTip, g.getFontRenderContext());
		g.setColor(TOOLTIP_COLOR);
		Rectangle2D bg = new Rectangle2D.Double(toolTipX - stringBounds.getWidth() / 2 - 4, toolTipY
				- stringBounds.getHeight() / 2 - 2, stringBounds.getWidth() + 5, Math.abs(stringBounds.getHeight()) + 3);
		g.fill(bg);
		g.setColor(Color.black);
		g.draw(bg);
		g.drawString(currentToolTip, (float) (toolTipX - stringBounds.getWidth() / 2) - 2, (float) (toolTipY + 3));
	}
}
 
Example 6
/**
 * Draws a string such that the specified anchor point is aligned to the 
 * given (x, y) location.
 *
 * @param text  the text.
 * @param g2  the graphics device.
 * @param x  the x coordinate (Java 2D).
 * @param y  the y coordinate (Java 2D).
 * @param anchor  the anchor location.
 * 
 * @return The text bounds (adjusted for the text position).
 */
public static Rectangle2D drawAlignedString(String text,
        Graphics2D g2, float x, float y, TextAnchor anchor) {

    Rectangle2D textBounds = new Rectangle2D.Double();
    float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, 
            textBounds);
    // adjust text bounds to match string position
    textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
        textBounds.getWidth(), textBounds.getHeight());
    g2.drawString(text, x + adjust[0], y + adjust[1]);
    return textBounds;
}
 
Example 7
Source Project: ET_Redux   File: GeoAgeLabel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param g2d
 */
public void paint(Graphics2D g2d) {
    
    g2d.setFont(new Font(
            "SansSerif",
            Font.PLAIN,
            10));
    
    Rectangle2D level1GeoAge = new Rectangle2D.Double(0, 0, width - 0.1, height - 0.1);
    g2d.draw(level1GeoAge);
    g2d.drawString(label, (float)1, (float)(height - 2));

}
 
Example 8
@Override
public void renderItemOverlay(Graphics2D graphics, int itemId, WidgetItem itemWidget)
{
	if (!config.showCoalBagOverlay() || (itemId != ItemID.COAL_BAG && itemId != ItemID.COAL_BAG_12019))
	{
		return;
	}

	graphics.setFont(FontManager.getRunescapeSmallFont());
	graphics.setColor(Color.WHITE);
	Point location = itemWidget.getCanvasLocation();

	graphics.drawString(config.amountOfCoalInCoalBag() + "", location.getX(), location.getY() + 14);
}
 
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
private static void draw(
    final Rectangle bounds,
    final Graphics2D graphics,
    final int x,
    final int y,
    final Image img,
    final String prod,
    final boolean drawFromTopLeft) {
  int normalizedY = y;
  if (img == null) {
    if (graphics.getFont().getSize() <= 0) {
      return;
    }
    if (drawFromTopLeft) {
      final FontMetrics fm = graphics.getFontMetrics();
      normalizedY += fm.getHeight();
    }
    graphics.drawString(prod, x - bounds.x, normalizedY - bounds.y);
  } else {
    // we want to be consistent
    // drawString takes y as the base line position
    // drawImage takes x as the top right corner
    if (!drawFromTopLeft) {
      normalizedY -= img.getHeight(null);
    }
    graphics.drawImage(img, x - bounds.x, normalizedY - bounds.y, null);
  }
}
 
Example 11
private void drawString(Graphics2D g2, int w, int h, boolean compressed) {
	if (progressBar.isStringPainted()) {
		// need to reduce font size to fit available space.
		// DO NOT CALL THIS EVERY TIME AS IT'S TREMENDOUSLY EXPENSIVE!!!
		if (compressed && progressBar.getFont().getSize() != 11) {
			progressBar.setFont(progressBar.getFont().deriveFont(11f));
		}
		FontMetrics fontSizer = progressBar.getFontMetrics(progressBar.getFont());

		String displayString = progressBar.getString();
		if (displayString == null || displayString.trim().isEmpty()) {
			return;
		}

		int stringHeight = fontSizer.getHeight();
		int stringWidth = fontSizer.stringWidth(displayString);

		// if string is too wide, cut beginning off until it fits
		while (stringWidth > w * 2) {
			displayString = displayString.substring(0, (int) (displayString.length() * 0.9));
			stringWidth = fontSizer.stringWidth(displayString);
		}

		g2.setColor(Colors.TEXT_FOREGROUND);
		if (compressed) {
			g2.drawString(displayString, (int) Math.max(0, w / 0.33 - w - stringWidth - 5), h - (h - stringHeight) / 2
					- 1);
		} else {
			g2.drawString(displayString, w - stringWidth, h + stringHeight - 1);
		}
	}
}
 
Example 12
public static void main(final String[] args) throws IOException {
    for (int  point = 5; point < 11; ++point) {
        Graphics2D g2d = bi.createGraphics();
        g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point));
        g2d.scale(scale, scale);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.green);
        g2d.drawString(TEXT, 0, 20);
        int length = g2d.getFontMetrics().stringWidth(TEXT);
        if (length < 0) {
            throw new RuntimeException("Negative length");
        }
        for (int i = (length + 1) * scale; i < width; ++i) {
            for (int j = 0; j < height; ++j) {
                if (bi.getRGB(i, j) != Color.white.getRGB()) {
                    g2d.drawLine(length, 0, length, height);
                    ImageIO.write(bi, "png", new File("image.png"));
                    System.out.println("length = " + length);
                    System.err.println("Wrong color at x=" + i + ",y=" + j);
                    System.err.println("Color is:" + new Color(bi.getRGB(i,
                                                                         j)));
                    throw new RuntimeException("Test failed.");
                }
            }
        }
        g2d.dispose();
    }
}
 
Example 13
public static void testTransformedFont(AffineTransform a, Object textHint) {
    BufferedImage bi = new BufferedImage(200, 200,
                               BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setFont(g2.getFont().deriveFont(12.0f));
    g2.setTransform(a);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textHint);
    g2.drawString("test", 100, 100);
}
 
Example 14
@Override
public void DoPaint(Graphics2D g) {
    int l = left;
    int t = top;

    if (!outroPintor) {
        if (getTipo() == tipoDrawer.tpMedida) {
            l = dono.getL() + left;
            t = dono.getT() + top;
        } else {
            l = dono.getL();
            t = dono.getT();
        }
    }
    if (!recivePaint) {
        if (isGradiente()) {
            g.setPaint(PaintGradiente(g, l, t));
        } else {
            g.setColor(getCor());
        }
    }

    Shape dr = null;
    boolean ok = false;
    int[] pts;
    switch (tipo) {
        case tpElipse:
            pts = ArrayDePontos(getElipse());
            if (pts.length == 4) {
                dr = new Ellipse2D.Double(pts[0], pts[1], pts[2], pts[3]);
            }
            break;
        case tpRetangulo:
            pts = ArrayDePontos(getRetangulo());
            if (pts.length == 4) {
                dr = new Rectangle2D.Double(pts[0], pts[1], pts[2], pts[3]);
            }
            if (pts.length == 6) {
                dr = new RoundRectangle2D.Double(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
            }
            break;
        case tpCurva:
            pts = ArrayDePontos(getCurva());
            if (pts.length == 8) {
                dr = new CubicCurve2D.Double(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5], pts[6], pts[7]);
            }
            if (pts.length == 6) {
                dr = new QuadCurve2D.Double(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
            }
            break;
        case tpArco:
            //        public final static int OPEN = 0;
            //        public final static int CHORD = 1;
            //        public final static int PIE = 2;
            pts = ArrayDePontos(getArco());
            if (pts.length == 7) {
                dr = new Arc2D.Double(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5], pts[6]);
            }
            break;
        case tpImagem:
            DrawImagem(g);
            ok = true;
            break;
        case tpMedida:
            //# Foi retirado do dezenho porque está feio (DrawerEditor).)
            if (vertical == VERTICAL) {
                medidaH(g, l, t);
            } else {
                medidaV(g, l, t);
            }
            ok = true;
            break;
        case tpPath:
            DrawComplexPath(g, l, t);
            ok = true;
            break;
        default:
            g.drawLine(l, t, getWidth(), getHeight());
            ok = true;
            break;
    }
    if (dr == null || ok) {
        if (dr == null && !ok) {
            g.drawString("?", l + 5, t + 5);
        }
        return;
    }
    if (isFill()) {
        g.fill(dr);
    } else {
        g.draw(dr);
    }
}
 
Example 15
private void modeSpecificDrawLine( Graphics2D g2, String line,
                                   int baseX, int baseY ) {
    /// ABP - keep track of old tform, restore it later
    AffineTransform oldTx = null;
    oldTx = g2.getTransform();
    g2.translate( baseX, baseY );
    g2.transform( getAffineTransform( g2Transform ) );

    switch ( drawMethod ) {
      case DRAW_STRING:
        g2.drawString( line, 0, 0 );
        break;
      case DRAW_CHARS:
        g2.drawChars( line.toCharArray(), 0, line.length(), 0, 0 );
        break;
      case DRAW_BYTES:
        try {
            byte lineBytes[] = line.getBytes( "ISO-8859-1" );
            g2.drawBytes( lineBytes, 0, lineBytes.length, 0, 0 );
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
        break;
      case DRAW_GLYPHV:
        GlyphVector gv =
          testFont.createGlyphVector( g2.getFontRenderContext(), line );
        g2.drawGlyphVector( gv, (float) 0, (float) 0 );
        break;
      case TL_DRAW:
        TextLayout tl = new TextLayout( line, testFont,
                                        g2.getFontRenderContext() );
        tl.draw( g2, (float) 0, (float) 0 );
        break;
      case GV_OUTLINE:
        GlyphVector gvo =
          testFont.createGlyphVector( g2.getFontRenderContext(), line );
        g2.draw( gvo.getOutline( (float) 0, (float) 0 ));
        break;
      case TL_OUTLINE:
        TextLayout tlo =
          new TextLayout( line, testFont,
                          g2.getFontRenderContext() );
        AffineTransform at = new AffineTransform();
        g2.draw( tlo.getOutline( at ));
    }

    /// ABP - restore old tform
    g2.setTransform ( oldTx );

}
 
Example 16
/**
 * 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( );
	}
}
 
Example 17
/**
 * Draws a tick on the dial.
 *
 * @param g2  the graphics device.
 * @param meterArea  the meter area.
 * @param value  the tick value.
 * @param label  a flag that controls whether or not a value label is drawn.
 */
protected void drawTick(Graphics2D g2, Rectangle2D meterArea,
                        double value, boolean label) {

    double valueAngle = valueToAngle(value);

    double meterMiddleX = meterArea.getCenterX();
    double meterMiddleY = meterArea.getCenterY();

    g2.setPaint(this.tickPaint);
    g2.setStroke(new BasicStroke(2.0f));

    double valueP2X;
    double valueP2Y;

    double radius = (meterArea.getWidth() / 2) + DEFAULT_BORDER_SIZE;
    double radius1 = radius - 15;

    double valueP1X = meterMiddleX
            + (radius * Math.cos(Math.PI * (valueAngle / 180)));
    double valueP1Y = meterMiddleY
            - (radius * Math.sin(Math.PI * (valueAngle / 180)));

    valueP2X = meterMiddleX
            + (radius1 * Math.cos(Math.PI * (valueAngle / 180)));
    valueP2Y = meterMiddleY
            - (radius1 * Math.sin(Math.PI * (valueAngle / 180)));

    Line2D.Double line = new Line2D.Double(valueP1X, valueP1Y, valueP2X,
            valueP2Y);
    g2.draw(line);

    if (this.tickLabelsVisible && label) {

        String tickLabel =  this.tickLabelFormat.format(value);
        g2.setFont(this.tickLabelFont);
        g2.setPaint(this.tickLabelPaint);

        FontMetrics fm = g2.getFontMetrics();
        Rectangle2D tickLabelBounds
            = TextUtilities.getTextBounds(tickLabel, g2, fm);

        double x = valueP2X;
        double y = valueP2Y;
        if (valueAngle == 90 || valueAngle == 270) {
            x = x - tickLabelBounds.getWidth() / 2;
        }
        else if (valueAngle < 90 || valueAngle > 270) {
            x = x - tickLabelBounds.getWidth();
        }
        if ((valueAngle > 135 && valueAngle < 225)
                || valueAngle > 315 || valueAngle < 45) {
            y = y - tickLabelBounds.getHeight() / 2;
        }
        else {
            y = y + tickLabelBounds.getHeight() / 2;
        }
        g2.drawString(tickLabel, (float) x, (float) y);
    }
}
 
Example 18
/**
 * Draws a tick on the dial.
 *
 * @param g2  the graphics device.
 * @param meterArea  the meter area.
 * @param value  the tick value.
 * @param label  a flag that controls whether or not a value label is drawn.
 */
protected void drawTick(Graphics2D g2, Rectangle2D meterArea,
                        double value, boolean label) {

    double valueAngle = valueToAngle(value);

    double meterMiddleX = meterArea.getCenterX();
    double meterMiddleY = meterArea.getCenterY();

    g2.setPaint(this.tickPaint);
    g2.setStroke(new BasicStroke(2.0f));

    double valueP2X;
    double valueP2Y;

    double radius = (meterArea.getWidth() / 2) + DEFAULT_BORDER_SIZE;
    double radius1 = radius - 15;

    double valueP1X = meterMiddleX
            + (radius * Math.cos(Math.PI * (valueAngle / 180)));
    double valueP1Y = meterMiddleY
            - (radius * Math.sin(Math.PI * (valueAngle / 180)));

    valueP2X = meterMiddleX
            + (radius1 * Math.cos(Math.PI * (valueAngle / 180)));
    valueP2Y = meterMiddleY
            - (radius1 * Math.sin(Math.PI * (valueAngle / 180)));

    Line2D.Double line = new Line2D.Double(valueP1X, valueP1Y, valueP2X,
            valueP2Y);
    g2.draw(line);

    if (this.tickLabelsVisible && label) {

        String tickLabel =  this.tickLabelFormat.format(value);
        g2.setFont(this.tickLabelFont);
        g2.setPaint(this.tickLabelPaint);

        FontMetrics fm = g2.getFontMetrics();
        Rectangle2D tickLabelBounds
            = TextUtilities.getTextBounds(tickLabel, g2, fm);

        double x = valueP2X;
        double y = valueP2Y;
        if (valueAngle == 90 || valueAngle == 270) {
            x = x - tickLabelBounds.getWidth() / 2;
        }
        else if (valueAngle < 90 || valueAngle > 270) {
            x = x - tickLabelBounds.getWidth();
        }
        if ((valueAngle > 135 && valueAngle < 225)
                || valueAngle > 315 || valueAngle < 45) {
            y = y - tickLabelBounds.getHeight() / 2;
        }
        else {
            y = y + tickLabelBounds.getHeight() / 2;
        }
        g2.drawString(tickLabel, (float) x, (float) y);
    }
}
 
Example 19
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 = 25;                     // 验证码图片的高度
        int codeCount = 4;                   // 验证码字符个数
        int codeX = width / (codeCount + 1); // 字符横向间距
        int codeY = height - 4;              // 字符纵向间距
        int fontHeight = height - 2;         // 字体高度
        int randomSeed = 10;                 // 随机数种子
        char[] codeSequence = {              // 验证码中可出现的字符
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
        };
        // 创建图像
        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 20
Source Project: RipplePower   File: GraphicsUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * 绘制指定文字
 * 
 * @param s
 * @param graphics2D
 * @param i
 * @param j
 * @param k
 */
public static void drawString(String message, Graphics2D graphics2D, int x, int y, int z) {
	Font font = graphics2D.getFont();
	int size = graphics2D.getFontMetrics(font).stringWidth(message);
	GraphicsUtils.setAlpha(graphics2D, 0.9f);
	graphics2D.drawString(message, x + (z - size) / 2, y);
	GraphicsUtils.setAlpha(graphics2D, 1.0f);
}