Java Code Examples for java.awt.Graphics2D.getFontRenderContext()

The following are Jave code examples for showing how to use getFontRenderContext() of the java.awt.Graphics2D class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: brModelo   File: DesenhadorDeTexto.java   View Source Code Vote up 6 votes
private LineBreakMeasurer[] getLineBreakMeasurers(Graphics2D g) {
    if (lbmTexto == null && (Texto != null && !Texto.equals(""))) {
        lbmTexto = new LineBreakMeasurer[Textos.length];
        for (int i = 0; i < lbmTexto.length; i++) {
            String tmp = Textos[i].isEmpty()? " " : Textos[i];
            AttributedString attribString = new AttributedString(tmp);
            attribString.addAttribute(TextAttribute.FONT, getFont());
            //attribString.addAttribute(TextAttribute.FONT, getFont());
            AttributedCharacterIterator attribCharIterator = attribString.getIterator();
            //FontRenderContext frc = new FontRenderContext(null, true, false);
            FontRenderContext frc = g.getFontRenderContext();
            lbmTexto[i] = new LineBreakMeasurer(attribCharIterator, frc);
        }
    }
    return lbmTexto;
}
 
Example 2
Project: Pogamut3   File: TrimmedLabelWidget.java   View Source Code Vote up 6 votes
private String getTrimmedText(String text, Graphics2D g, double maxWidth) {
	FontRenderContext frc = g.getFontRenderContext();
	Rectangle2D rect = getFont().getStringBounds(text, frc);

	if (rect.getWidth() <= maxWidth)
		return text;

	text += "...";
	do {
		text = text.replaceFirst(".\\.\\.\\.$", "...");

		rect = getFont().getStringBounds(text, frc);
	} while (rect.getWidth() > maxWidth && text.length() > 4);

	return text;
}
 
Example 3
Project: litiengine   File: SpeechBubble.java   View Source Code Vote up 5 votes
@Override
public void render(final Graphics2D g) {
  if (this.displayedText == null || this.displayedText.isEmpty() || !Game.getRenderEngine().canRender(this.entity)) {
    return;
  }

  final Point2D location = Game.getCamera().getViewPortLocation(this.entity);
  RenderEngine.renderImage(g, this.bubble, new Point2D.Double(location.getX() + this.entity.getWidth() / 2.0 - this.textBoxWidth / 2.0 - PADDING, location.getY() - this.height - PADDING));

  g.setColor(SPEAK_FONT_COLOR);
  final FontRenderContext frc = g.getFontRenderContext();

  final String text = this.displayedText;
  final AttributedString styledText = new AttributedString(text);
  styledText.addAttribute(TextAttribute.FONT, this.font);
  final AttributedCharacterIterator iterator = styledText.getIterator();
  final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
  measurer.setPosition(0);
  final float x = (float) Game.getCamera().getViewPortLocation(this.entity).getX() + this.entity.getWidth() / 2.0f - this.textBoxWidth / 2.0f;
  float y = (float) Game.getCamera().getViewPortLocation(this.entity).getY() - this.height;
  while (measurer.getPosition() < text.length()) {
    final TextLayout layout = measurer.nextLayout(this.textBoxWidth);

    y += layout.getAscent();
    final float dx = layout.isLeftToRight() ? 0 : this.textBoxWidth - layout.getAdvance();
    layout.draw(g, x + dx, y);
    y += layout.getDescent() + layout.getLeading();
  }
}
 
Example 4
Project: oscm   File: ImageProducer.java   View Source Code Vote up 5 votes
protected BufferedImage createImage(Color bgColor) {
    BufferedImage bufferedImage = new BufferedImage(END_X, END_Y,
            BufferedImage.TYPE_INT_RGB);
    // create graphics and graphics2d
    final Graphics graphics = bufferedImage.getGraphics();
    final Graphics2D g2d = (Graphics2D) graphics;

    // set the background color
    g2d.setBackground(bgColor == null ? Color.gray : bgColor);
    g2d.clearRect(START_X, START_Y, END_X, END_Y);
    // create a pattern for the background
    createPattern(g2d);
    // set the fonts and font rendering hints
    Font font = new Font("Helvetica", Font.ITALIC, 30);
    g2d.setFont(font);
    FontRenderContext frc = g2d.getFontRenderContext();
    g2d.translate(10, 24);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setStroke(new BasicStroke(3));

    // sets the foreground color
    g2d.setPaint(Color.DARK_GRAY);
    GlyphVector gv = font.createGlyphVector(frc, message);
    int numGlyphs = gv.getNumGlyphs();
    for (int ii = 0; ii < numGlyphs; ii++) {
        AffineTransform at;
        Point2D p = gv.getGlyphPosition(ii);
        at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
        at.rotate(Math.PI / 8);
        Shape shape = gv.getGlyphOutline(ii);
        Shape sss = at.createTransformedShape(shape);
        g2d.fill(sss);
    }
    return blurImage(bufferedImage);
}
 
Example 5
Project: QN-ACTR-Release   File: JmtCell.java   View Source Code Vote up 5 votes
/**
 * Return Cell's real size (this method considers Icon and name size)
 * @param graph <code>JGraph</code> object to retrive font dimension informations
 * @return cell's real size
 *
 * Bertoli Marco  4-giu-2005
 */
public Dimension getSize(JGraph graph) {
	Dimension cellDimension = (Dimension) imageDimension.clone();
	// Gets the graph font
	Font font = graph.getFont();
	// Gets the graphical context
	Graphics2D g2D = (Graphics2D) graph.getGraphics();
	// Gets the bounds of the cell name
	FontRenderContext frc = g2D.getFontRenderContext();
	Rectangle r = font.getStringBounds(getUserObject().toString(), frc).getBounds();
	// Sets the cell dimension
	cellDimension.height += r.height + 5;
	cellDimension.width = Math.max(cellDimension.width, r.width + 10);
	return cellDimension;
}
 
Example 6
Project: openjdk-jdk10   File: FontDisposeTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception
{
    // The bug only happens with Type 1 fonts. The Ghostscript font files
    // should be commonly available. From distro pacakge or
    //  ftp://ftp.gnu.org/gnu/ghostscript/gnu-gs-fonts-other-6.0.tar.gz
    // Pass pfa/pfb font file as argument
    String path = args[0];

    // Load
    InputStream stream = new FileInputStream(path);
    Font font = Font.createFont(Font.TYPE1_FONT,stream);

    // Ensure native bits have been generated
    BufferedImage img = new BufferedImage(100,100,
                             BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    FontRenderContext frc = g2d.getFontRenderContext();

    font.getLineMetrics("derp",frc);

    // Force disposal -
    // System.gc() is not sufficient.
    Field font2DHandleField = Font.class.getDeclaredField("font2DHandle");
    font2DHandleField.setAccessible(true);
    sun.font.Font2DHandle font2DHandle =
                  (sun.font.Font2DHandle)font2DHandleField.get(font);

    sun.font.Font2D font2D = font2DHandle.font2D;
    sun.font.Type1Font type1Font = (sun.font.Type1Font)font2D;

    Method getScalerMethod =
    sun.font.Type1Font.class.getDeclaredMethod("getScaler");
    getScalerMethod.setAccessible(true);
    sun.font.FontScaler scaler =
              (sun.font.FontScaler)getScalerMethod.invoke(type1Font);

    // dispose should not crash due to double free
    scaler.dispose();
}
 
Example 7
Project: parabuild-ci   File: DateAxis.java   View Source Code Vote up 5 votes
/**
 * 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) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();

    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 8
Project: hearthstone   File: JLabelAtributos.java   View Source Code Vote up 5 votes
@Override
protected void paintComponent(Graphics g) {
    atualizar();
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setFont(FONT);
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout textLayout = new TextLayout(Integer.toString(value), FONT, frc);
    g2.setPaint(textColor);
    Shape outline = textLayout.getOutline(AffineTransform.getTranslateInstance(value < 10 ? 20 : type == SHIELD ? 10 : 14, 30));
    g2.fill(outline);
    g2.setPaint(BLACK);
    g2.draw(outline);
}
 
Example 9
Project: parabuild-ci   File: DateAxis.java   View Source Code Vote up 5 votes
/**
 * 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 10
Project: Mafia   File: TextElement.java   View Source Code Vote up 4 votes
public static float grabMaxTextSize(String textToFit, int widthConstraint, int heightConstraint, Graphics2D g) {
	float textSize = 1;
	
	
	while(true) {
		g.setFont(FontResources.mainFont.deriveFont(textSize));
		
		FontRenderContext frc = g.getFontRenderContext();
		Rectangle2D bounds = g.getFont().getStringBounds(textToFit, frc);
		
		int textWidth = (int) bounds.getWidth();
		int textHeight = (int) bounds.getHeight();
		
		
		if(textWidth < widthConstraint && textHeight < heightConstraint)
			textSize ++;
		else
			break;
	}
	
	
	return textSize;
}
 
Example 11
Project: openjdk-jdk10   File: TextTests.java   View Source Code Vote up 4 votes
public void init(TestEnvironment env, Result results){
    super.init(env, results);
    g2d = (Graphics2D)graphics;
    frc = g2d.getFontRenderContext();
}
 
Example 12
Project: jdk8u-jdk   File: FontPanel.java   View Source Code Vote up 4 votes
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 13
Project: openjdk-jdk10   File: FontPanel.java   View Source Code Vote up 4 votes
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 14
Project: FreeCol   File: Canvas.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public void paintComponent(Graphics g) {
    updateSizes();
    Graphics2D g2d = (Graphics2D) g;
    chatDisplay.removeOldMessages();
    Dimension size = getSize();

    if (freeColClient.isMapEditor()) {
        if (hasMap()) {
            mapViewer.displayMap(g2d);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }

    } else if (freeColClient.isInGame() && hasMap()) {
        mapViewer.displayMap(g2d);

        // Grey out the map if it is not my turn (and a multiplayer game).
        if (!freeColClient.currentPlayerIsMyPlayer()) {
            if (greyLayer == null) {
                greyLayer = new GrayLayer(freeColClient);
            }
            if (greyLayer.getParent() == null) {
                add(greyLayer, JLayeredPane.DRAG_LAYER);
            }
            greyLayer.setBounds(0, 0, size.width, size.height);
            greyLayer.setPlayer(freeColClient.getGame().getCurrentPlayer());
        } else {
            if (greyLayer != null && greyLayer.getParent() != null) {
                removeFromCanvas(greyLayer);
            }
        }

        // paint chat display
        chatDisplay.display(g2d, mapViewer.getImageLibrary(), size);

    } else {
        /* main menu */
        // TODO: Check if its right to sometimes have an unfocused map
        //       ingame and end up here after clicking outside map.
        final String bgImageKey = "image.flavor.Canvas.map";
        if (ResourceManager.hasImageResource(bgImageKey)) {
            // Get the background without scaling, to avoid wasting
            // memory needlessly keeping an unbounded number of rescaled
            // versions of the largest image in FreeCol, forever.
            final Image bgImage = ResourceManager.getImage(bgImageKey);
            // Draw background image with scaling.
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(bgImage, 0, 0, size.width, size.height, this);
            String versionStr = "v. " + FreeCol.getVersion();
            Font oldFont = g2d.getFont();
            Color oldColor = g2d.getColor();
            Font newFont = oldFont.deriveFont(Font.BOLD);
            TextLayout layout = new TextLayout(versionStr, newFont,
                g2d.getFontRenderContext());
            Rectangle2D bounds = layout.getBounds();
            float x = size.width - (float) bounds.getWidth() - 5;
            float y = size.height - (float) bounds.getHeight();
            g2d.setColor(Color.white);
            layout.draw(g2d, x, y);
            g2d.setFont(oldFont);
            g2d.setColor(oldColor);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }
    }
}
 
Example 15
Project: freecol   File: Canvas.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public void paintComponent(Graphics g) {
    updateSizes();
    Graphics2D g2d = (Graphics2D) g;
    chatDisplay.removeOldMessages();
    Dimension size = getSize();

    if (freeColClient.isMapEditor()) {
        if (hasMap()) {
            mapViewer.displayMap(g2d);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }

    } else if (freeColClient.isInGame() && hasMap()) {
        mapViewer.displayMap(g2d);

        // Grey out the map if it is not my turn (and a multiplayer game).
        if (!freeColClient.currentPlayerIsMyPlayer()) {
            if (greyLayer == null) {
                greyLayer = new GrayLayer(freeColClient);
            }
            if (greyLayer.getParent() == null) {
                add(greyLayer, JLayeredPane.DRAG_LAYER);
            }
            greyLayer.setBounds(0, 0, size.width, size.height);
            greyLayer.setPlayer(freeColClient.getGame().getCurrentPlayer());
        } else {
            if (greyLayer != null && greyLayer.getParent() != null) {
                removeFromCanvas(greyLayer);
            }
        }

        // paint chat display
        chatDisplay.display(g2d, mapViewer.getImageLibrary(), size);

    } else {
        /* main menu */
        // TODO: Check if its right to sometimes have an unfocused map
        //       ingame and end up here after clicking outside map.
        final String bgImageKey = "image.flavor.Canvas.map";
        if (ResourceManager.hasImageResource(bgImageKey)) {
            // Get the background without scaling, to avoid wasting
            // memory needlessly keeping an unbounded number of rescaled
            // versions of the largest image in FreeCol, forever.
            final Image bgImage = ResourceManager.getImage(bgImageKey);
            // Draw background image with scaling.
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(bgImage, 0, 0, size.width, size.height, this);
            String versionStr = "v. " + FreeCol.getVersion();
            Font oldFont = g2d.getFont();
            Color oldColor = g2d.getColor();
            Font newFont = oldFont.deriveFont(Font.BOLD);
            TextLayout layout = new TextLayout(versionStr, newFont,
                g2d.getFontRenderContext());
            Rectangle2D bounds = layout.getBounds();
            float x = size.width - (float) bounds.getWidth() - 5;
            float y = size.height - (float) bounds.getHeight();
            g2d.setColor(Color.white);
            layout.draw(g2d, x, y);
            g2d.setFont(oldFont);
            g2d.setColor(oldColor);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, size.width, size.height);
        }
    }
}
 
Example 16
Project: OpenJSharp   File: TextTests.java   View Source Code Vote up 4 votes
public void init(TestEnvironment env, Result results){
    super.init(env, results);
    g2d = (Graphics2D)graphics;
    frc = g2d.getFontRenderContext();
}
 
Example 17
Project: openjdk-jdk10   File: StyledFontLayoutTest.java   View Source Code Vote up 4 votes
private static void runTest() {
    im = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = im.createGraphics();
    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, W, H);
    g2d.setColor(Color.black);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    char[] chs = "Sample Text.".toCharArray();
    int len = chs.length;

    int x = 50, y = 100;

    FontRenderContext frc = g2d.getFontRenderContext();
    Font plain = new Font("Serif", Font.PLAIN, 48);
    GlyphVector pgv = plain.layoutGlyphVector(frc, chs, 0, len, 0);
    g2d.setFont(plain);
    g2d.drawChars(chs, 0, len, x, y); y +=50;

    g2d.drawGlyphVector(pgv, x, y); y += 50;
    Rectangle2D plainStrBounds = plain.getStringBounds(chs, 0, len, frc);
    Rectangle2D plainGVBounds = pgv.getLogicalBounds();
    Font bold = new Font("Serif", Font.BOLD, 48);
    GlyphVector bgv = bold.layoutGlyphVector(frc, chs, 0, len, 0);
    Rectangle2D boldStrBounds = bold.getStringBounds(chs, 0, len, frc);
    Rectangle2D boldGVBounds = bgv.getLogicalBounds();
    g2d.setFont(bold);
    g2d.drawChars(chs, 0, len, x, y); y +=50;
    g2d.drawGlyphVector(bgv, x, y);
    System.out.println("Plain String Bounds = " + plainStrBounds);
    System.out.println("Bold String Bounds = " + boldStrBounds);
    System.out.println("Plain GlyphVector Bounds = " + plainGVBounds);
    System.out.println("Bold GlyphVector Bounds = " + boldGVBounds);
    if (!plainStrBounds.equals(boldStrBounds) &&
         plainGVBounds.equals(boldGVBounds))
    {
        System.out.println("Test failed: Plain GV bounds same as Bold");
        if (!interactive) {
            throw new RuntimeException("Plain GV bounds same as Bold");
        }
    }

}
 
Example 18
Project: OpenJSharp   File: FontPanel.java   View Source Code Vote up 4 votes
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 19
Project: jdk8u-jdk   File: TextTests.java   View Source Code Vote up 4 votes
public void init(TestEnvironment env, Result results){
    super.init(env, results);
    g2d = (Graphics2D)graphics;
    frc = g2d.getFontRenderContext();
}
 
Example 20
Project: openjdk-jdk10   File: FontPanel.java   View Source Code Vote up 4 votes
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}