草庐IT

java - Windows 和 Linux 加载 ttf 字体时 JLabel 的差异

coder 2023-09-02 原文

我正在使用以下代码在 java 中上传 aller 字体:

private Font loadFont(final String path) {
    Font font = null;

    InputStream fontFile = null;
    fontFile = FontLoaderClass.class.getResourceAsStream(path);

    if (fontFile != null) {
        try {
            font = Font.createFont(Font.PLAIN, fontFile);
        } catch (FontFormatException e) {
            LOGGER.error("Error with font format {}", e);
        } catch (IOException e) {
            LOGGER.error("Error accessing font {}", e);
        }
    }
    return font;
}

字体加载正确:

http://www.fontsquirrel.com/fonts/Aller

字体设置为所有“.font”,更改了 java 应用程序的默认设置,但在 Linux 中可以正确显示,但 Windows 不能。

private Font buildFont(final String key, final int size) {
    Font f = loadFont(ALLER_LT_FONT_PATH);
    GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(f);
    if (f == null) {
        f = (Font) UIManager.get(key);
    }
    f = f.deriveFont(Font.TRUETYPE_FONT, size);
    return f;
}

Linux 显示:

Windows 显示:

如您在图像中所见,Windows 中有一些截断导致图像无法正确显示。

有没有人以前遇到过这个问题?

最佳答案

附上两个小demo,分别为Swing组件的绘制操作启用抗锯齿。

用于 Swing 组件

// to enable antialiasing (AA) for Swing components
//
// either:
//    start the JVM with the option -Dawt.useSystemAAFontSettings=on
//    see also: http://docs.oracle.com/javase/6/docs/technotes/guides/2d/flags.html#aaFonts
// or:
//    System.setProperty("awt.useSystemAAFontSettings", "on");
//    - you must call it before the first Swing component is rendered
//    - if AA it's on by default you must set it "off", otherwise you can't
//      toggle it inside the application

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_OFF;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;

public class SwingAntiAliasingDemo {

    public static void main(String[] args) {
        System.setProperty("awt.useSystemAAFontSettings", "off");
        initGui();
    }

    public static void initGui() {
        JFrame frame = new JFrame();

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        Font font = new Font("Serif", Font.TRUETYPE_FONT, 96);
        JPanel jpanel = new JPanel(new BorderLayout());

        JLabel labelAA = new JLabel("Antialiasing ON") {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D graphics2d = (Graphics2D) g;
                graphics2d.setRenderingHint(KEY_ANTIALIASING,
                        VALUE_ANTIALIAS_ON);
                super.paintComponent(g);
            }
        };
        labelAA.setFont(font);
        labelAA.setForeground(Color.WHITE);

        JLabel labelNoAA = new JLabel("Antialiasing OFF") {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D graphics2d = (Graphics2D) g;
                graphics2d.setRenderingHint(KEY_ANTIALIASING,
                        VALUE_ANTIALIAS_OFF);
                super.paintComponent(g);
            }
        };
        labelNoAA.setFont(font);
        labelNoAA.setForeground(Color.WHITE);

        jpanel.setBackground(new Color(0, 22, 95));
        jpanel.add(labelAA, BorderLayout.NORTH);
        jpanel.add(labelNoAA, BorderLayout.SOUTH);

        frame.setTitle("stackoverflow question 16304254");
        frame.getContentPane().add(jpanel);
        frame.setLocation(200, 200);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

绘制操作

// to enable antialiasing (AA) for draw operations

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;

import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_OFF;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;

public class DrawAntiAliasingDemo extends JFrame {

    private Font font;
    private Color backGroundColor;

    public static void main(String[] args) {
        new DrawAntiAliasingDemo();
    }

    public DrawAntiAliasingDemo() {
        font = new Font("Serif", Font.TRUETYPE_FONT, 96);
        backGroundColor = new Color(0, 22, 95);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        setTitle("stackoverflow question 16304254");
        setSize(850, 260);
        setResizable(false);
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D d = (Graphics2D) g;
        d.setColor(backGroundColor);
        d.fillRect(0, 0, getWidth(), getHeight());
        d.setFont(font);
        d.setPaint(Color.white);

        d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
        d.drawString("Antialiasing ON", 10, 115);

        d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_OFF);
        d.drawString("Antialiasing OFF", 10, 230);
    }
}

干杯 弗兰克

关于java - Windows 和 Linux 加载 ttf 字体时 JLabel 的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304254/

有关java - Windows 和 Linux 加载 ttf 字体时 JLabel 的差异的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  3. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  4. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  5. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  6. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  7. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐