下面列出了java.awt.Font#deriveFont ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void init(Action al) {
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder());
setBorderPainted(false);
setFocusPainted(false);
setFocusable(false);
setContentAreaFilled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setModel(new Model());
if (null != al) {
addActionListener(al);
setForeground(ColorManager.getDefault().getLinkColor());
} else {
setEnabled(false);
setForeground(ColorManager.getDefault().getDisabledColor());
}
Font font = UIManager.getFont("Tree.font");//NOI18N
if (underlined) {
Map<TextAttribute, Object> map = new HashMap<TextAttribute, Object>();
map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
font = font.deriveFont(map);
}
setFont(font);
}
public JavaFontRenderingBox(String str, int type, float size, Font f, boolean kerning) {
this.size = size;
if (kerning && KERNING != null) {
Map<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
map.put(KERNING, KERNING_ON);
map.put(LIGATURES, LIGATURES_ON);
f = f.deriveFont(map);
}
this.text = new TextLayout(str, f.deriveFont(type), TEMPGRAPHIC.getFontRenderContext());
Rectangle2D rect = text.getBounds();
this.height = (float) (-rect.getY() * size / 10);
this.depth = (float) (rect.getHeight() * size / 10) - this.height;
this.width = (float) ((rect.getWidth() + rect.getX() + 0.4f) * size / 10);
}
public FontPanel( Font2DTest demo, JFrame f ) {
f2dt = demo;
parent = f;
verticalBar = new JScrollBar ( JScrollBar.VERTICAL );
fc = new FontCanvas();
this.setLayout( new BorderLayout() );
this.add( "Center", fc );
this.add( "East", verticalBar );
verticalBar.addAdjustmentListener( this );
this.addComponentListener( new ComponentAdapter() {
public void componentResized( ComponentEvent e ) {
updateBackBuffer = true;
updateFontMetrics = true;
}
});
/// Initialize font and its infos
testFont = new Font(fontName, fontStyle, (int)fontSize);
if ((float)((int)fontSize) != fontSize) {
testFont = testFont.deriveFont(fontSize);
}
updateFontInfo();
}
/**
* Fetches and returns default button font nonstatic
*
* @return Font to default buttons to
* @throws java.io.IOException if unable to load font
*/
private Font getMenuFontInternal() throws IOException {
Font ret;
try (InputStream tmp = this.getClass().getResourceAsStream(PGTUtil.BUTTON_FONT_LOCATION)) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ret = Font.createFont(Font.TRUETYPE_FONT, tmp);
ret = ret.deriveFont((float) 12); // default to size 12 font
if (ret != null) {
ge.registerFont(ret);
}
} catch (Exception e) {
throw new IOException("Unable to load button font.", e);
}
return ret;
}
/**
* Attempts to load the given font from the OS's font folder (due to Java's
* ligature problems)
*
* @param fontFamily
* @return returns loaded font file on success, null otherwise
*/
public static Font loadFontFromOSFileFolder(String fontFamily) {
Font ret = null;
try {
File fontFile = getFontFile(fontFamily);
if (fontFile != null && fontFile.exists()) {
ret = Font.createFont(Font.TRUETYPE_FONT, fontFile);
Map attributes = ret.getAttributes();
attributes.put(TextAttribute.LIGATURES, TextAttribute.LIGATURES_ON);
ret = ret.deriveFont(attributes);
}
} catch (Exception e) {
IOHandler.writeErrorLog(e);
// do nothing here. Failure means returning null
}
return ret;
}
/**
* @inheritDoc
*/
@Override
public Object createValue(UIDefaults defaults) {
Font f = defaults.getFont(parentKey);
if (f != null) {
// always round size for now so we have exact int font size
// (or we may have lame looking fonts)
float size = Math.round(f.getSize2D() * sizeOffset);
int style = f.getStyle();
if (bold != null) {
if (bold.booleanValue()) {
style = style | Font.BOLD;
} else {
style = style & ~Font.BOLD;
}
}
if (italic != null) {
if (italic.booleanValue()) {
style = style | Font.ITALIC;
} else {
style = style & ~Font.ITALIC;
}
}
return f.deriveFont(style, size);
} else {
return null;
}
}
@Override
protected FontMetrics getFontMetrics() {
Font font = tabPane.getFont();
// selected tab is bold, to avoid resizing always assume bold and make tabs bigger
font = font.deriveFont(Font.BOLD);
return tabPane.getFontMetrics(font);
}
/**
* @param font The font to scale.
* @return The scaled font.
*/
public Font scale(Font font) {
if (mScale == 1) {
return font;
}
return font.deriveFont((float) (font.getSize() * mScale));
}
public static void addText(Graphics2D g, String text,
Font font, Color color, int x, int y,
float opacity, int shadow, int angle,
boolean isOutline) {
try {
AffineTransform saveAT = g.getTransform();
AffineTransform affineTransform = new AffineTransform();
affineTransform.rotate(Math.toRadians(angle), 0, 0);
Font rotatedFont = font.deriveFont(affineTransform);
if (shadow > 0) { // Not blurred. Can improve
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g.setColor(Color.GRAY);
g.setFont(rotatedFont);
g.drawString(text, x + shadow, y + shadow);
}
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
g.setColor(color);
g.setFont(rotatedFont);
if (isOutline) {
FontRenderContext frc = g.getFontRenderContext();
TextLayout textTl = new TextLayout(text, rotatedFont, frc);
Shape outline = textTl.getOutline(null);
AffineTransform transform = g.getTransform();
transform.translate(x, y);
g.transform(transform);
g.draw(outline);
} else {
g.drawString(text, x, y);
}
g.setTransform(saveAT);
} catch (Exception e) {
logger.error(e.toString());
}
}
public int measureText( String text )
throws FontFormatException, IOException
{
URL fontURL =
new URL( Jenkins.getInstance().pluginManager.getPlugin( "status-badges" ).baseResourceURL,
"fonts/verdana.ttf" );
InputStream fontStream = fontURL.openStream();
Font defaultFont = Font.createFont( Font.TRUETYPE_FONT, fontStream );
defaultFont = defaultFont.deriveFont( 11f );
Canvas canvas = new Canvas();
FontMetrics fontMetrics = canvas.getFontMetrics( defaultFont );
return fontMetrics.stringWidth( text );
}
public static Font createTrueType(InputStream in, int size) throws IOException, FontFormatException {
assert (in != null);
Font font = Font.createFont(Font.TRUETYPE_FONT, in);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
return font.deriveFont(Font.PLAIN, size);
}
public void setFontParams(String name, float size,
int style, int transform) {
boolean fontModified = false;
if ( !name.equals( fontName ) || style != fontStyle )
fontModified = true;
fontName = name;
fontSize = size;
fontStyle = style;
fontTransform = transform;
/// Recreate the font as specified
testFont = new Font(fontName, fontStyle, (int)fontSize);
if ((float)((int)fontSize) != fontSize) {
testFont = testFont.deriveFont(fontSize);
}
if ( fontTransform != NONE ) {
AffineTransform at = getAffineTransform( fontTransform );
testFont = testFont.deriveFont( at );
}
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
if ( fontModified ) {
/// Tell main panel to update the font info
updateFontInfo();
f2dt.fireUpdateFontInfo();
}
}
/**
* Font used to render force elements (units).
* @param size
* @return
*/
public Font getUnitFont(float size)
{
//load font from resource
InputStream fontStream = _instance.getClass().getClassLoader().getResourceAsStream("FONTS/UnitFont.ttf");
//InputStream fontStream = _unitFontStream;
Font newFont = null;
try
{
//create font
newFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
}
catch(FontFormatException ffe)
{
ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
new RendererException("UnitFont failed to load.", ffe));
}
catch(IOException ioe)
{
ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
new RendererException("UnitFont failed to load.", ioe));
}
catch(Exception exc)
{
ErrorLogger.LogException(this.getClass().getName() ,"getUnitFont()",
new RendererException("UnitFont failed to load.", exc));
}
//resize font
newFont = newFont.deriveFont(Font.TRUETYPE_FONT, size);
//return font
return newFont;
}
public static void main(String[] args) throws Exception {
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();
BufferedImage bi = new BufferedImage(500, 500,
BufferedImage.TYPE_INT_RGB);
for (AntialiasHint antialiasHint : antialiasHints) {
for (Font f : fonts) {
for (StyleAndSize styleAndSize : stylesAndSizes) {
f = f.deriveFont(styleAndSize.style, styleAndSize.size);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
antialiasHint.getHint());
FontMetrics fm = g2d.getFontMetrics(f);
int[] width;
int maxWidth = -1;
int maxAdvance = fm.getMaxAdvance();
if (debug) {
System.out.println("Testing " + f + " in " +
antialiasHint);
System.out.println("getMaxAdvance: " + maxAdvance);
}
if (maxAdvance != -1) {
String failureMessage = null;
width = fm.getWidths();
for (int j = 0; j < width.length; j++) {
if (width[j] > maxWidth) {
maxWidth = width[j];
}
if (width[j] > maxAdvance) {
failureMessage = "FAILED: getMaxAdvance is " +
"not max for font: " +
f.toString() +
" getMaxAdvance(): " +
maxAdvance +
" getWidths()[" + j + "]: " +
width[j];
throw new Exception(failureMessage);
}
}
}
if (debug) {
System.out.println("Max char width: " + maxWidth);
System.out.println("PASSED");
System.out.println(".........................");
}
}
}
}
System.out.println("TEST PASS - OK");
}
public void init(TestEnvironment env, Result result) {
// graphics
graphics = env.getGraphics();
// text
String sname = (String)env.getModifier(tscriptList);
int slen = env.getIntValue(tlengthList);
text = getString(sname, slen);
// chars
chars = text.toCharArray();
// font
String fname = (String)env.getModifier(fnameList);
if ("Physical".equals(fname)) {
fname = physicalFontNameFor(sname, slen, text);
}
int fstyle = env.getIntValue(fstyleList);
float fsize = ((Float)env.getModifier(fsizeList)).floatValue();
AffineTransform ftx = (AffineTransform)env.getModifier(ftxList);
font = new Font(fname, fstyle, (int)fsize);
if (hasGraphics2D) {
if (fsize != Math.floor(fsize)) {
font = font.deriveFont(fsize);
}
if (!ftx.isIdentity()) {
font = font.deriveFont(ftx);
}
}
// graphics
if (hasGraphics2D) {
Graphics2D g2d = (Graphics2D)graphics;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
env.getModifier(taaList));
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
env.isEnabled(tfmTog)
? RenderingHints.VALUE_FRACTIONALMETRICS_ON
: RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
env.isEnabled(gaaTog)
? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.transform((AffineTransform)env.getModifier(gtxList));
}
// set result
result.setUnits(text.length());
result.setUnitName("char");
}
public static Font title(Font f)
{
// XXX In Japanese, bold is not used and hardly readeable if small, just
// use gothic/non gothic instead.
return f.deriveFont(Font.BOLD);
}
/**
* Create a scaled {@code Font} where the scale factor is provided
* explicitly in the parameter.
* The equivalent of regular text, which would only complicate the
* source code and slow down the game if used, would be:
* createFont(FontType.NORMAL, FontSize.TINY, Font.PLAIN,
* gui.getImageLibrary().getScalingFactor());
*
* @param fontType How the font should look like.
* @param fontSize Its relative size.
* @param style The font style for choosing plain, bold or italic.
* @param scaleFactor The applied scale factor.
* @return The created Font.
*/
public static Font createFont(FontType fontType, FontSize fontSize,
int style, float scaleFactor) {
float scaledSize = calcScaledSize(fontSize, scaleFactor);
String fontKey = getFontKey(fontType);
Font font = (fontKey == null)
? mainFont
: ResourceManager.getFont(fontKey);
return font.deriveFont(style, scaledSize);
}
/**
* Checks to see if the font size override setting is enabled and adjusts
* the given font as necessary to match the override setting. If the setting
* is not enabled, then <code>font</code> is returned.
*
* @param font
* The current font to adjust, if necessary.
* @return a font object with the proper size.
*/
public static Font adjustForFontSizeOverride(Font font) {
if (FONT_SIZE_OVERRIDE_VALUE == null) {
return font;
}
return font.deriveFont((float) FONT_SIZE_OVERRIDE_VALUE.intValue());
}
/**
* For bold italic font.
*
* @param f
* base font
*/
public static Font bold_italic(Font f)
{
return f.deriveFont(Font.BOLD | Font.ITALIC);
}
/**
* For less important text, like grayed out italic.
*
* @param f
* base font
*/
public static Font less(Font f)
{
return f.deriveFont(Font.ITALIC);
}