C# 和 Java 中字体的等效外观
我需要用 Java 模拟 С# 的字体绘制。结果是:
Graphics g =this.CreateGraphics();
Font f = new Font("Courier New", 24, FontStyle.Regular, GraphicsUnit.Document);
g.FillRectangle(new SolidBrush(Color.White),0,0,400,400 );
g.DrawLine(new Pen(Color.Black), 0, 100, 200, 100);
g.DrawString("Hey go!", f, new SolidBrush(Color.Black), 0, 100);
我重新计算了字体大小,但 java 字体看起来有点变形。
Font f = new Font("Courier New", Font.PLAIN, 24 * 120 / 300).deriveFont((float) (24 * 120. / 300.));
FontRenderContext fontRenderContext = new FontRenderContext(null, false, true);
TextLayout textLayout = new TextLayout("Hey go!", f, fontRenderContext);
Graphics graphics = contentPane.getGraphics();
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0, 0, 400, 400);
graphics.setColor(new Color(0, 0, 0));
graphics.drawLine(0, 100, 200, 100);
graphics.setFont(f);
Color c = new Color(0, 0, 0);
graphics.setColor(c);
textLayout.draw((Graphics2D) graphics, 0, 100);
我可以做些什么来使输出看起来相同吗? PS:我已经更新了代码,因为我发现了一个错误。 右键单击图像即可在浏览器中逐像素查看它们。
I need to emulate С#'s font drawing in Java. The result is:
Graphics g =this.CreateGraphics();
Font f = new Font("Courier New", 24, FontStyle.Regular, GraphicsUnit.Document);
g.FillRectangle(new SolidBrush(Color.White),0,0,400,400 );
g.DrawLine(new Pen(Color.Black), 0, 100, 200, 100);
g.DrawString("Hey go!", f, new SolidBrush(Color.Black), 0, 100);
I've recalculated font size but java font looks a bit destorted.
Font f = new Font("Courier New", Font.PLAIN, 24 * 120 / 300).deriveFont((float) (24 * 120. / 300.));
FontRenderContext fontRenderContext = new FontRenderContext(null, false, true);
TextLayout textLayout = new TextLayout("Hey go!", f, fontRenderContext);
Graphics graphics = contentPane.getGraphics();
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0, 0, 400, 400);
graphics.setColor(new Color(0, 0, 0));
graphics.drawLine(0, 100, 200, 100);
graphics.setFont(f);
Color c = new Color(0, 0, 0);
graphics.setColor(c);
textLayout.draw((Graphics2D) graphics, 0, 100);
Can I do something to make output look the same?
PS: I've updated the code, since I've found an error.
Rightclick images to see them pixel-to-pixel in your browser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是你渲染文本两次,有一些细微的差别。
第一次使用
TextLayout
,第二次直接绘制字符串。TextLayout
使用构造函数中最后一个参数指定的fractionalMetrics
,而drawString
方法则不然。因此,您使用不同的设置绘制字符串两次,结果是字符串显示出微弱的阴影。
删除对
drawString
的第二次调用,选择是否喜欢fractionalMetrics
就可以了。It's just that you render the text twice with some little differences.
First time you use the
TextLayout
and second time directly draw the string. TheTextLayout
usesfractionalMetrics
as specified by the last parameter in the constructor which thedrawString
method doesn't.Therefore you draw the string two times with different settings and the result is that the string shows this faint shadow.
Remove the second call to
drawString
, choose whether you likefractionalMetrics
or not and you'll be just fine.