Java HTML rendering “pt” vs. “px” sizes

ⅰ亾dé卋堺 提交于 2021-02-10 05:14:33

问题


I ran into an issue with specifying a html element's width in a JLabel and thought I would run it up the flag pole here and see if anyone had any advice.

When I specify the width of an element using a "px" unit value, the resulting size is actually ~133%, whereas if I don't use a unit, or use "pt", I get the exact size I specified.

In the below example, if you change the "width: 100px" to "width: 100pt", you will get the right size.

This answer https://stackoverflow.com/a/6257861/131795 seems to be related, and the 72 dpi adjustment seems to match with the mismatch that I'm seeing in in my example.

I might be raging against an ancient piece of code here, but why is an absolute px value being converted and a pt value being treated as absolute?

public class test {
    public static void main(String args[]) {
        JFrame frame = new JFrame();

        JLabel label = new JLabel("<html><div style='width: 100px; background-color: red;'>test</div>");
        frame.getContentPane().add(label);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 200);
        frame.setVisible(true);
    }
}

回答1:


Ok, I think I've found the 'reason' (or culprit) for java scaling pixel values.

In the HTMLEditorKit implementation, there is a CSS class that handles css stuff. It has a table with scaling values for each supported unit. (starting on line 2843 in CSS.class)

For "pt", it is 1-to-1 mapping. For "px", its 1-to-1.3 mapping. There is even a comment that says:

// Not sure about 1.3, determined by experiementation.

There are actually two mapping tables, where the second one is used if the w3c mode is turned on. It has scaling modes that are backwards from the first table:

For "pt", it is 1-to-screenres/72dpi. For "px", its 1-to-1 mapping.

I'm not sure what activates the w3c mode, but beware of the issue.



来源:https://stackoverflow.com/questions/56380978/java-html-rendering-pt-vs-px-sizes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!