Java Code Examples for java.awt.font.LineMetrics

The following are top voted examples for showing how to use java.awt.font.LineMetrics. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   View source code 9 votes vote down vote up
private void showTextOnStream(IFontTextDrawerEnv env, PDPageContentStream contentStream, Font attributeFont,
		PDFont font, boolean isStrikeThrough, boolean isUnderline, boolean isLigatures, String text)
		throws IOException {
	if (isStrikeThrough || isUnderline) {
		// noinspection unused
		float stringWidth = font.getStringWidth(text);
		// noinspection unused
		LineMetrics lineMetrics = attributeFont.getLineMetrics(text, env.getFontRenderContext());
		/*
		 * TODO: We can not draw that yet, we must do that later. While in textmode its
		 * not possible to draw lines...
		 */
	}
	// noinspection StatementWithEmptyBody
	if (isLigatures) {
		/*
		 * No idea how to map this ...
		 */
	}
	contentStream.showText(text);
}
 
Example 2
Project: openjdk-jdk10   File: UnderlineTest.java   View source code 7 votes vote down vote up
public void paintComponent(Graphics g) {
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, fpd.width, fpd.height);

    g.setColor(Color.RED);
    FontRenderContext frc = ((Graphics2D)g).getFontRenderContext();
    LineMetrics lm = f.getLineMetrics(fps, frc);
    int h = (int)(fpd.height - 20 - lm.getAscent());
    g.drawLine(20, h, fpd.width - 20, h);
    h = fpd.height - 20;
    g.drawLine(20, h, fpd.width - 20, h);
    h = (int)(fpd.height - 20 + lm.getDescent());
    g.drawLine(20, h, fpd.width - 20, h);

    g.setColor(Color.BLACK);
    g.setFont(f);
    g.drawString(fps, 50, fpd.height - 20);
}
 
Example 3
Project: jtk   File: PlotPanel.java   View source code 6 votes vote down vote up
public void paintToRect(Graphics2D g2d, int x, int y, int w, int h) {
  g2d = createGraphics(g2d,x,y,w,h);
  g2d.setRenderingHint(
    RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
  Font font = g2d.getFont();
  FontMetrics fm = g2d.getFontMetrics();
  FontRenderContext frc = g2d.getFontRenderContext();
  LineMetrics lm = font.getLineMetrics(text,frc);
  //int fh = round(lm.getHeight());
  //int fa = round(lm.getAscent());
  int fd = round(lm.getDescent());
  int wt = fm.stringWidth(text);
  int xt = max(0,(w-wt)/2);
  int yt = h-1-2*fd;
  g2d.drawString(text,xt,yt);
  g2d.dispose();
}
 
Example 4
Project: OpenJSharp   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
public Rectangle2D getLogicalBounds() {
    setFRCTX();
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 5
Project: OpenJSharp   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
@Override
public Rectangle2D getLogicalBounds() {
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length() > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 6
Project: vars-annotation   File: ImageArchiveServiceDecorator.java   View source code 6 votes vote down vote up
/**
 * Add overlay text to the image and save as a .jpg file.
 *
 * @param  image        a java.awt.Image to add the text overlay to
 * @param  overlayText  The text to overlay onto the image
 * @return
 */
public static BufferedImage createImageWithOverlay(final Image image, final String[] overlayText) {

    // Copy BufferedImage and set .jpg file name
    final BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.drawImage(image, 0, 0, null);
    final Font font = new Font("Monospaced", Font.PLAIN, 14);
    g.setFont(font);
    g.setColor(Color.CYAN);
    final FontRenderContext frc = g.getFontRenderContext();
    int x = 1;
    int n = 1;
    for (String s : overlayText) {
        LineMetrics lineMetrics = font.getLineMetrics(s, frc);
        float y = (lineMetrics.getHeight() + 1) * n + lineMetrics.getHeight();
        g.drawString(s, x, y);
        n++;
    }

    g.dispose();

    return bi;
}
 
Example 7
Project: parabuild-ci   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * 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 8
Project: parabuild-ci   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * 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 9
Project: jdk8u-jdk   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
public Rectangle2D getLogicalBounds() {
    setFRCTX();
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 10
Project: openjdk-jdk10   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
public Rectangle2D getLogicalBounds() {
    setFRCTX();
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 11
Project: g2   File: ChangeableAttributedString.java   View source code 6 votes vote down vote up
public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("{text=");
    for (int i = 0; i < length(); i++) {
        buf.append(aStrings[i].getIterator().current());
    }
    final String RS = "\n\t";
    buf.append(RS);
    for (int i = 0; i < length(); i++) {
        buf.append(bounds[i].toString());
        final String FS = " ";
        final LineMetrics m = metrics[i];
        // height = ascent + descent + leading
        buf.append(" ascent=").append(m.getAscent()).append(FS);
        buf.append("descent=").append(m.getDescent()).append(FS);
        buf.append("leading=").append(m.getLeading()).append(FS);

        buf.append(RS);
    }
    buf.append("}");
    return buf.toString();
}
 
Example 12
Project: openjdk9   File: ExtendedTextSourceLabel.java   View source code 6 votes vote down vote up
private void finishInit() {
  font = source.getFont();

  Map<TextAttribute, ?> atts = font.getAttributes();
  baseTX = AttributeValues.getBaselineTransform(atts);
  if (baseTX == null){
      cm = source.getCoreMetrics();
  } else {
    AffineTransform charTX = AttributeValues.getCharTransform(atts);
    if (charTX == null) {
        charTX = new AffineTransform();
    }
    font = font.deriveFont(charTX);

    LineMetrics lm = font.getLineMetrics(source.getChars(), source.getStart(),
        source.getStart() + source.getLength(), source.getFRC());
    cm = CoreMetrics.get(lm);
  }
}
 
Example 13
Project: openjdk9   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
public Rectangle2D getLogicalBounds() {
    setFRCTX();
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 14
Project: openjdk9   File: UnderlineTest.java   View source code 6 votes vote down vote up
public void paintComponent(Graphics g) {
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, fpd.width, fpd.height);

    g.setColor(Color.RED);
    FontRenderContext frc = ((Graphics2D)g).getFontRenderContext();
    LineMetrics lm = f.getLineMetrics(fps, frc);
    int h = (int)(fpd.height - 20 - lm.getAscent());
    g.drawLine(20, h, fpd.width - 20, h);
    h = fpd.height - 20;
    g.drawLine(20, h, fpd.width - 20, h);
    h = (int)(fpd.height - 20 + lm.getDescent());
    g.drawLine(20, h, fpd.width - 20, h);

    g.setColor(Color.BLACK);
    g.setFont(f);
    g.drawString(fps, 50, fpd.height - 20);
}
 
Example 15
Project: ccu-historian   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * 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 16
Project: ccu-historian   File: TextFragment.java   View source code 6 votes vote down vote up
/**
 * Calculates the vertical offset between the baseline and the specified 
 * text anchor.
 * 
 * @param g2  the graphics device.
 * @param anchor  the anchor.
 * 
 * @return the offset.
 */
public float calculateBaselineOffset(Graphics2D g2, TextAnchor anchor) {
    float result = 0.0f;
    final FontMetrics fm = g2.getFontMetrics(this.font);
    final LineMetrics lm = fm.getLineMetrics("ABCxyz", g2);
    if (anchor.isTop()) {
        result = lm.getAscent();
    }
    else if (anchor.isHalfAscent()) {
        result = lm.getAscent() / 2.0f;
    }
    else if (anchor.isVerticalCenter()) {
        result = lm.getAscent() / 2.0f - lm.getDescent() / 2.0f;
    }
    else if (anchor.isBottom()) {
        result = -lm.getDescent() - lm.getLeading();
    }
    return result;                                             
}
 
Example 17
Project: ccu-historian   File: TextUtilities.java   View source code 6 votes vote down vote up
/**
 * Returns the bounds for the specified text.
 *
 * @param text  the text (<code>null</code> permitted).
 * @param g2  the graphics context (not <code>null</code>).
 * @param fm  the font metrics (not <code>null</code>).
 *
 * @return The text bounds (<code>null</code> if the <code>text</code>
 *         argument is <code>null</code>).
 */
public static Rectangle2D getTextBounds(String text, Graphics2D g2, 
        FontMetrics fm) {

    Rectangle2D bounds;
    if (TextUtilities.useFontMetricsGetStringBounds) {
        bounds = fm.getStringBounds(text, g2);
        // getStringBounds() can return incorrect height for some Unicode
        // characters...see bug parade 6183356, let's replace it with
        // something correct
        LineMetrics lm = fm.getFont().getLineMetrics(text,
                g2.getFontRenderContext());
        bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
                lm.getHeight());
    }
    else {
        double width = fm.stringWidth(text);
        double height = fm.getHeight();
        if (logger.isDebugEnabled()) {
            logger.debug("Height = " + height);
        }
        bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
                height);
    }
    return bounds;
}
 
Example 18
Project: intellij-ce-playground   File: TextPainter.java   View source code 6 votes vote down vote up
private double drawHeaderOrFooterLine(Graphics2D g, double x, double y, double w, String headerText,
                                      String alignment) {
  FontRenderContext fontRenderContext = g.getFontRenderContext();
  LineMetrics lineMetrics = getHeaderFooterLineMetrics(g);
  float lineHeight = lineMetrics.getHeight();
  if (myPerformActualDrawing) {
    headerText = convertHeaderText(headerText);
    g.setFont(myHeaderFont);
    g.setColor(Color.black);
    float descent = lineMetrics.getDescent();
    double width = myHeaderFont.getStringBounds(headerText, fontRenderContext).getWidth() + getCharWidth(g);
    float yPos = (float) (lineHeight - descent + y);
    if (PrintSettings.LEFT.equals(alignment)) {
      drawStringToGraphics(g, headerText, x, yPos);
    } else if (PrintSettings.CENTER.equals(alignment)) {
      drawStringToGraphics(g, headerText, (float) (x + (w - width) / 2), yPos);
    } else if (PrintSettings.RIGHT.equals(alignment)) {
      drawStringToGraphics(g, headerText, (float) (x + w - width), yPos);
    }
  }
  return lineHeight;
}
 
Example 19
Project: jfreechart   File: TextUtils.java   View source code 6 votes vote down vote up
/**
 * Returns the bounds for the specified text.
 *
 * @param text  the text ({@code null} permitted).
 * @param g2  the graphics context (not {@code null}).
 * @param fm  the font metrics (not {@code null}).
 *
 * @return The text bounds ({@code null} if the {@code text}
 *         argument is {@code null}).
 */
public static Rectangle2D getTextBounds(String text, Graphics2D g2, 
        FontMetrics fm) {

    Rectangle2D bounds;
    if (TextUtils.useFontMetricsGetStringBounds) {
        bounds = fm.getStringBounds(text, g2);
        // getStringBounds() can return incorrect height for some Unicode
        // characters...see bug parade 6183356, let's replace it with
        // something correct
        LineMetrics lm = fm.getFont().getLineMetrics(text,
                g2.getFontRenderContext());
        bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
                lm.getHeight());
    }
    else {
        double width = fm.stringWidth(text);
        double height = fm.getHeight();
        bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
                height);
    }
    return bounds;
}
 
Example 20
Project: jfreechart   File: TextFragment.java   View source code 6 votes vote down vote up
/**
 * Calculates the vertical offset between the baseline and the specified 
 * text anchor.
 * 
 * @param g2  the graphics device.
 * @param anchor  the anchor.
 * 
 * @return the offset.
 */
public float calculateBaselineOffset(Graphics2D g2, TextAnchor anchor) {
    float result = 0.0f;
    FontMetrics fm = g2.getFontMetrics(this.font);
    LineMetrics lm = fm.getLineMetrics("ABCxyz", g2);
    if (anchor.isTop()) {
        result = lm.getAscent();
    }
    else if (anchor.isHalfAscent()) {
        result = lm.getAscent() / 2.0f;
    }
    else if (anchor.isVerticalCenter()) {
        result = lm.getAscent() / 2.0f - lm.getDescent() / 2.0f;
    }
    else if (anchor.isBottom()) {
        result = -lm.getDescent() - lm.getLeading();
    }
    return result;                                             
}
 
Example 21
Project: jfreechart   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * 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 = TextUtils.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 22
Project: eSDK_EC_SDK_Java   File: MyButton.java   View source code 6 votes vote down vote up
private void paintButton(Graphics g, Color[] colors) {
	
	Graphics2D g2 = (Graphics2D) g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	int width = this.getWidth();
	int height = this.getHeight();

	Point2D center = new Point2D.Float(width / 2, height / 2);
	float radius = width / 2;
	float[] dist = { 0.0f, 0.8f };
	RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
	g2.setPaint(paint);
	shape = new RoundRectangle2D.Double(0, 0, width, height, height, height);
	g2.fill(shape);

	Font defaultFont = getFont();
	g2.setFont(defaultFont);
	g2.setColor(Color.BLACK);
	Rectangle2D rect = defaultFont.getStringBounds(text, g2.getFontRenderContext());
	LineMetrics lineMetrics = defaultFont.getLineMetrics(text, g2.getFontRenderContext());
	g2.drawString(text, (float) (width / 2 - rect.getWidth() / 2), (float) ((height / 2)
			+ ((lineMetrics.getAscent() + lineMetrics.getDescent()) / 2 - lineMetrics.getDescent())));

}
 
Example 23
Project: eSDK_EC_SDK_Java   File: MyButton.java   View source code 6 votes vote down vote up
private void paintButton(Graphics g, Color[] colors) {
	
	Graphics2D g2 = (Graphics2D) g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	int width = this.getWidth();
	int height = this.getHeight();

	Point2D center = new Point2D.Float(width / 2, height / 2);
	float radius = width / 2;
	float[] dist = { 0.0f, 0.8f };
	RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
	g2.setPaint(paint);
	shape = new RoundRectangle2D.Double(0, 0, width, height, height, height);
	g2.fill(shape);

	Font defaultFont = getFont();
	g2.setFont(defaultFont);
	g2.setColor(Color.BLACK);
	Rectangle2D rect = defaultFont.getStringBounds(text, g2.getFontRenderContext());
	LineMetrics lineMetrics = defaultFont.getLineMetrics(text, g2.getFontRenderContext());
	g2.drawString(text, (float) (width / 2 - rect.getWidth() / 2), (float) ((height / 2)
			+ ((lineMetrics.getAscent() + lineMetrics.getDescent()) / 2 - lineMetrics.getDescent())));

}
 
Example 24
Project: eSDK_EC_SDK_Java   File: MyButton.java   View source code 6 votes vote down vote up
private void paintButton(Graphics g, Color[] colors) {
	
	Graphics2D g2 = (Graphics2D) g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	int width = this.getWidth();
	int height = this.getHeight();

	Point2D center = new Point2D.Float(width / 2, height / 2);
	float radius = width / 2;
	float[] dist = { 0.0f, 0.8f };
	RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
	g2.setPaint(paint);
	shape = new RoundRectangle2D.Double(0, 0, width, height, height, height);
	g2.fill(shape);

	Font defaultFont = getFont();
	g2.setFont(defaultFont);
	g2.setColor(Color.BLACK);
	Rectangle2D rect = defaultFont.getStringBounds(text, g2.getFontRenderContext());
	LineMetrics lineMetrics = defaultFont.getLineMetrics(text, g2.getFontRenderContext());
	g2.drawString(text, (float) (width / 2 - rect.getWidth() / 2), (float) ((height / 2)
			+ ((lineMetrics.getAscent() + lineMetrics.getDescent()) / 2 - lineMetrics.getDescent())));

}
 
Example 25
Project: eSDK_EC_SDK_Java   File: CTDFrame.java   View source code 6 votes vote down vote up
private void paintButton(Graphics g, Color[] colors)
{
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int width = this.getWidth();
    int height = this.getHeight();

    Point2D center = new Point2D.Float(width / 2, height / 2);
    float radius = width / 2;
    float[] dist = {0.0f, 0.8f};
    RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
    g2.setPaint(paint);
    shape = new RoundRectangle2D.Double(0, 0, width, height, height, height);
    g2.fill(shape);

    Font defaultFont = getFont();
    g2.setFont(defaultFont);
    g2.setColor(Color.BLACK);
    Rectangle2D rect = defaultFont.getStringBounds(text, g2.getFontRenderContext());
    LineMetrics lineMetrics = defaultFont.getLineMetrics(text, g2.getFontRenderContext());
    g2.drawString(text,
        (float)(width / 2 - rect.getWidth() / 2),
        (float)((height / 2) + ((lineMetrics.getAscent() + lineMetrics.getDescent()) / 2 - lineMetrics.getDescent())));

}
 
Example 26
Project: eSDK_EC_SDK_Java   File: MyButton.java   View source code 6 votes vote down vote up
private void paintButton(Graphics g, Color[] colors) {
	
	Graphics2D g2 = (Graphics2D) g;
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	int width = this.getWidth();
	int height = this.getHeight();

	Point2D center = new Point2D.Float(width / 2, height / 2);
	float radius = width / 2;
	float[] dist = { 0.0f, 0.8f };
	RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
	g2.setPaint(paint);
	shape = new RoundRectangle2D.Double(0, 0, width, height, height, height);
	g2.fill(shape);

	Font defaultFont = getFont();
	g2.setFont(defaultFont);
	g2.setColor(Color.BLACK);
	Rectangle2D rect = defaultFont.getStringBounds(text, g2.getFontRenderContext());
	LineMetrics lineMetrics = defaultFont.getLineMetrics(text, g2.getFontRenderContext());
	g2.drawString(text, (float) (width / 2 - rect.getWidth() / 2), (float) ((height / 2)
			+ ((lineMetrics.getAscent() + lineMetrics.getDescent()) / 2 - lineMetrics.getDescent())));

}
 
Example 27
Project: aya-lang   File: MarkerAxisBand.java   View source code 6 votes vote down vote up
/**
 * 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 28
Project: pumpernickel   File: JLink.java   View source code 6 votes vote down vote up
@Override
public void paint(Graphics g) {
  super.paint(g);
	
	if(drawLine) {
		LineMetrics m = getFont().getLineMetrics(getText(),frc);
		Insets i = getInsets();
		int descent = (int)m.getDescent()-4;
		if(isEnabled()) {
			g.setColor(getForeground());
		} else {
			g.setColor(SystemColor.textInactiveText);
		}
		g.drawLine(i.left,getHeight()-i.bottom-descent,getWidth()-i.right-1,getHeight()-i.bottom-descent);
	}
}
 
Example 29
Project: Push2Display   File: GVTLineMetrics.java   View source code 6 votes vote down vote up
/**
 * Constructs a GVTLineMetrics object based on the specified line metrics
 * with a scale factor applied.
 *
 * @param lineMetrics The lineMetrics object that this metrics object will
 * be based upon.
 * @param scaleFactor The scale factor to apply to all metrics.
 */
public GVTLineMetrics(LineMetrics lineMetrics, float scaleFactor) {
    this.ascent = lineMetrics.getAscent() * scaleFactor;
    this.baselineIndex = lineMetrics.getBaselineIndex();
    this.baselineOffsets = lineMetrics.getBaselineOffsets();
    for (int i=0; i<baselineOffsets.length; i++) {
        this.baselineOffsets[i] *= scaleFactor;
    }
    this.descent = lineMetrics.getDescent() * scaleFactor;
    this.height = lineMetrics.getHeight() * scaleFactor;
    this.leading = lineMetrics.getLeading();
    this.numChars = lineMetrics.getNumChars();
    this.strikethroughOffset = 
        lineMetrics.getStrikethroughOffset() * scaleFactor;
    this.strikethroughThickness = 
        lineMetrics.getStrikethroughThickness() * scaleFactor;
    this.underlineOffset = lineMetrics.getUnderlineOffset() * scaleFactor;
    this.underlineThickness = 
        lineMetrics.getUnderlineThickness() * scaleFactor;
    this.overlineOffset = -this.ascent;
    this.overlineThickness = this.underlineThickness;
}
 
Example 30
Project: lookaside_java-1.8.0-openjdk   File: ExtendedTextSourceLabel.java   View source code 6 votes vote down vote up
private void finishInit() {
  font = source.getFont();

  Map<TextAttribute, ?> atts = font.getAttributes();
  baseTX = AttributeValues.getBaselineTransform(atts);
  if (baseTX == null){
      cm = source.getCoreMetrics();
  } else {
    AffineTransform charTX = AttributeValues.getCharTransform(atts);
    if (charTX == null) {
        charTX = new AffineTransform();
    }
    font = font.deriveFont(charTX);

    LineMetrics lm = font.getLineMetrics(source.getChars(), source.getStart(),
        source.getStart() + source.getLength(), source.getFRC());
    cm = CoreMetrics.get(lm);
  }
}
 
Example 31
Project: jdk8u_jdk   File: ExtendedTextSourceLabel.java   View source code 6 votes vote down vote up
private void finishInit() {
  font = source.getFont();

  Map<TextAttribute, ?> atts = font.getAttributes();
  baseTX = AttributeValues.getBaselineTransform(atts);
  if (baseTX == null){
      cm = source.getCoreMetrics();
  } else {
    AffineTransform charTX = AttributeValues.getCharTransform(atts);
    if (charTX == null) {
        charTX = new AffineTransform();
    }
    font = font.deriveFont(charTX);

    LineMetrics lm = font.getLineMetrics(source.getChars(), source.getStart(),
        source.getStart() + source.getLength(), source.getFRC());
    cm = CoreMetrics.get(lm);
  }
}
 
Example 32
Project: lookaside_java-1.8.0-openjdk   File: StandardGlyphVector.java   View source code 6 votes vote down vote up
public Rectangle2D getLogicalBounds() {
    setFRCTX();
    initPositions();

    LineMetrics lm = font.getLineMetrics("", frc);

    float minX, minY, maxX, maxY;
    // horiz only for now...
    minX = 0;
    minY = -lm.getAscent();
    maxX = 0;
    maxY = lm.getDescent() + lm.getLeading();
    if (glyphs.length > 0) {
        maxX = positions[positions.length - 2];
    }

    return new Rectangle2D.Float(minX, minY, maxX - minX, maxY - minY);
}
 
Example 33
Project: g2   File: ChangeableAttributedString.java   View source code 6 votes vote down vote up
/**
 * Given an attributed string and the graphics environment it lives in, pull it apart into its components.
 *
 * @param g2      graphics
 * @param aString attributed String
 */
protected ChangeableAttributedString(Graphics2D g2, AttributedString aString, int kerning) {
    this.kerning = kerning;
    AttributedCharacterIterator iter = aString.getIterator();
    int n = iter.getEndIndex();
    aStrings = new AttributedString[n];
    bounds = new Rectangle2D[n];
    metrics = new LineMetrics[n];

    for (int i = iter.getBeginIndex(); i < iter.getEndIndex(); i++) {
        iter.setIndex(i);
        aStrings[i] = new AttributedString(iter, i, i + 1);
        Font font = (Font) iter.getAttribute(TextAttribute.FONT);
        if (font != null) {
            g2.setFont(font); // needed for getFont, -and- getFontRenderContext
        }
        final FontRenderContext frc = g2.getFontRenderContext();

        bounds[i] = g2.getFont().getStringBounds(iter, i, i + 1, frc);

        metrics[i] = g2.getFont().getLineMetrics((new Character(iter.current())).toString(),
                frc);
    }

}
 
Example 34
Project: intellij-ce-playground   File: ASGallery.java   View source code 6 votes vote down vote up
private void paintLabel(Graphics g, int cell, Rectangle cellBounds, @Nullable String label, int thumbnailHeight) {
  if (!StringUtil.isEmpty(label)) {
    final Color fg;
    if (hasFocus() && cell == mySelectedIndex && (getImage(cell) != null || UIUtil.isUnderDarcula())) {
      fg = UIUtil.getTreeSelectionForeground();
    }
    else {
      fg = UIUtil.getTreeForeground();
    }
    GraphicsUtil.setupAntialiasing(g);
    g.setColor(fg);
    FontMetrics fontMetrics = g.getFontMetrics();
    LineMetrics metrics = fontMetrics.getLineMetrics(label, g);
    int width = fontMetrics.stringWidth(label);

    int textBoxTop = myCellMargin.top + thumbnailHeight;
    int cellBottom = cellBounds.height - myCellMargin.bottom;

    int textY = cellBounds.y + (cellBottom + textBoxTop + (int)(metrics.getHeight() - metrics.getDescent())) / 2 ;
    int textX = (cellBounds.width - myCellMargin.left - myCellMargin.right - width) / 2 + cellBounds.x + myCellMargin.left;
    g.drawString(label, textX, textY);
  }
}
 
Example 35
Project: incubator-netbeans   File: FontInfo.java   View source code 5 votes vote down vote up
FontInfo(Font origFont, JTextComponent textComponent, FontRenderContext frc, float rowHeightCorrection, int textZoom) {
    renderFont = (textZoom != 0)
            ? new Font(origFont.getName(), origFont.getStyle(), Math.max(origFont.getSize() + textZoom, 1))
            : origFont;
    char defaultChar = 'A';
    String defaultCharText = String.valueOf(defaultChar);
    TextLayout defaultCharTextLayout = new TextLayout(defaultCharText, renderFont, frc); // NOI18N
    TextLayout rowHeightTextLayout = new TextLayout("A_|B", renderFont, frc);
    // Round the ascent to eliminate long mantissa without any visible effect on rendering.
    updateRowHeight(rowHeightTextLayout, rowHeightCorrection);
    // Ceil fractions to whole numbers since this measure may be used for background rendering
    charWidth = (float) Math.ceil(defaultCharTextLayout.getAdvance());
    LineMetrics lineMetrics = renderFont.getLineMetrics(defaultCharText, frc);
    underlineAndStrike[0] = lineMetrics.getUnderlineOffset() * rowHeightCorrection;
    underlineAndStrike[1] = lineMetrics.getUnderlineThickness();
    underlineAndStrike[2] = lineMetrics.getStrikethroughOffset() * rowHeightCorrection;
    underlineAndStrike[3] = lineMetrics.getStrikethroughThickness();
    if (LOG.isLoggable(Level.FINE)) {
        FontMetrics fm = textComponent.getFontMetrics(origFont); // From original font
        LOG.fine("Orig Font=" + origFont + // NOI18N
                "\n  " + this + ", charWidth=" + charWidth + ", textZoom=" + textZoom + // NOI18N
                "\n  rowHeightCorrection=" + rowHeightCorrection + // NOI18N
                ", underlineO/T=" + underlineAndStrike[0] + "/" + underlineAndStrike[1] + // NOI18N
                ", strikethroughO/T=" + underlineAndStrike[2] + "/" + underlineAndStrike[3] + // NOI18N
                "\n  FontMetrics (for comparison; without-RHC): fm-line-height=" + fm.getHeight() + // NOI18N
                ", fm-ascent,descent,leading=" + fm.getAscent() + "," + fm.getDescent() + "," + fm.getLeading() + // NOI18N
                "\n"); // NOI18N
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.log(Level.FINEST, "FontInfo creation stacktrace", new Exception()); // NOI18N
        }
    }
}
 
Example 36
Project: jaer   File: CollapsablePanel.java   View source code 5 votes vote down vote up
protected void paintComponent(Graphics g) {  
            super.paintComponent(g);  
            Graphics2D g2 = (Graphics2D) g;  
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                    RenderingHints.VALUE_ANTIALIAS_ON);  
            int h = getHeight();  
            int width = getWidth();
        	Polygon arrow = new Polygon();
//        	Polygon leftArrow = new Polygon();

//                g2.drawImage(closed, PAD, 0, h, h, this); 
            g2.setFont(font);  
            FontRenderContext frc = g2.getFontRenderContext();  
            LineMetrics lm = font.getLineMetrics(title, frc);  
            float height = lm.getAscent() + lm.getDescent();  
            float x = OFFSET;  
            float y = (h + height) / 2 - lm.getDescent();  
            g2.drawString(title, x, y);
            int th = ((int)height)-2;
            if (selected) {
            	arrow.addPoint(width - 3*th/2 + 1, h/2 - th/4);
            	arrow.addPoint(width - th/2 - 1, h/2 - th/4);
            	arrow.addPoint(width - th, h/2 + th/4 );
            	g2.fillPolygon(arrow);
            }
//                g2.drawImage(open, PAD, 0, h, h, this); 
            else { 
            	arrow.addPoint(width - 3*th/4, h/2 - (th-2)/2);
            	arrow.addPoint(width - 3*th/4, h/2 + (th-2)/2);
            	arrow.addPoint(width - 5*th/4, h /2);
            	g2.fillPolygon(arrow);
            }
        }
 
Example 37
Project: parabuild-ci   File: MeterLegend.java   View source code 5 votes vote down vote up
/**
 * Creates a legend item
 *
 * @param graphics  the graphics device.
 * @param item  the legend item.
 * @param x  the x coordinate.
 * @param y  the y coordinate.
 *
 * @return the legend item.
 */
private DrawableLegendItem createLegendItem(Graphics graphics,
                                            LegendItem item, double x, double y) {

    int innerGap = 2;
    FontMetrics fm = graphics.getFontMetrics();
    LineMetrics lm = fm.getLineMetrics(item.getLabel(), graphics);
    float textHeight = lm.getHeight();

    DrawableLegendItem drawable = new DrawableLegendItem(item);

    float xloc = (float) (x + innerGap + 1.15f * textHeight);
    float yloc = (float) (y + innerGap + (textHeight - lm.getLeading() - lm.getDescent()));

    drawable.setLabelPosition(new Point2D.Float(xloc, yloc));

    float boxDim = textHeight * 0.70f;
    xloc = (float) (x + innerGap + 0.15f * textHeight);
    yloc = (float) (y + innerGap + 0.15f * textHeight);

    drawable.setMarker(new Rectangle2D.Float(xloc, yloc, boxDim, boxDim));

    float width = (float) (drawable.getLabelPosition().getX() - x
                           + fm.stringWidth(item.getLabel()) + 0.5 * textHeight);

    float height = 2 * innerGap + textHeight;
    drawable.setBounds(x, y, width, height);
    return drawable;

}
 
Example 38
Project: parabuild-ci   File: DateAxis.java   View source code 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we just look at two
 * values: the lower bound and the upper bound for the axis.  These two values will usually
 * be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return the estimated maximum width of the tick labels.
 */
private double estimateMaximumTickLabelWidth(Graphics2D g2, DateTickUnit unit) {

    Insets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.left + tickLabelInsets.right;

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr = null;
        String upperStr = null;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 39
Project: parabuild-ci   File: DateAxis.java   View source code 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we just look at two
 * values: the lower bound and the upper bound for the axis.  These two values will usually
 * be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return the estimated maximum width of the tick labels.
 */
private double estimateMaximumTickLabelHeight(Graphics2D g2, DateTickUnit unit) {

    Insets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.top + tickLabelInsets.bottom;

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (!isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr = null;
        String upperStr = null;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example 40
Project: parabuild-ci   File: NumberAxis.java   View source code 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we just look at two
 * values: the lower bound and the upper bound for the axis.  These two values will usually
 * be representative.
 *
 * @param g2  the graphics device.
 * @param tickUnit  the tick unit to use for calculation.
 *
 * @return the estimated maximum width of the tick labels.
 */
protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit tickUnit) {

    Insets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.left + tickLabelInsets.right;

    if (isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of the font)...
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
        Range range = getRange();
        double lower = range.getLowerBound();
        double upper = range.getUpperBound();
        String lowerStr = tickUnit.valueToString(lower);
        String upperStr = tickUnit.valueToString(upper);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}