【问题标题】:How to get the exact Font out of Fontfamily?如何从 Fontfamily 中获取确切的字体?
【发布时间】:2014-12-16 12:36:40
【问题描述】:

我想创建一个 Picturebox,使其形状适应特定字体的字符串。我需要这个,以便以后可以创建文本并将其放置在 AxWindowsMediaPlayer 控件上。

因此我创建了以下类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using System.Drawing;

namespace myProject
{
    class ShapedPictureBoxes : PictureBox
    {
        public ShapedPictureBoxes()
        {
            this.Paint += this.shapedPaint;
        }

    void shapedPaint(object sender, PaintEventArgs e)
    {
        System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();


Font font = new Font("Arial", 14f);
float emSize = e.Graphics.DpiY*font.Size/72;
        graphicsPath.AddString(text, new FontFamily("Arial"), (int)System.Drawing.FontStyle.Regular, emSize, new Point(0,0), new StringFormat());

        e.Graphics.DrawString(text, font, Brushes.Red, new Point(0, 0));

        this.Region = new Region(graphicsPath);
    }

    public string text = "Here comes the sun, doo da doo do";
}

}

现在的问题是,“Graphics.DrawString”与 graphicspath.AddString 不匹配,可能是因为 FontFamily 与 Font 不同。我怎样才能匹配它们?

那么:如何将 Fontfamily 转换为 Font 或反之亦然?

看起来是这样的:

【问题讨论】:

    标签: c# fonts picturebox font-family


    【解决方案1】:

    您需要考虑以下事实:Font 的大小以点为单位指定,而AddString() 的大小以设备为单位指定。

    您可以按如下方式转换单位:

    Font font = new Font("Arial", 14f, FontStyle.Bold);
    float emSize = e.Graphics.DpiY * font.Size / 72; // Here's the conversion.
    graphicsPath.AddString(text, new FontFamily("Arial"), (int)System.Drawing.FontStyle.Bold, emSize, new Point(0, 0), new StringFormat());
    

    请注意,我将计算出的emSize 传递给AddString(),而不是传递14f

    【讨论】:

    • 现在看起来好多了:我用你的部分解决方案调整了这个问题并添加了一张图片......
    • @Salocin 我刚刚注意到您的AddString() 使用的是粗体,但您的字体不是。我已经更新了我的示例,因此字体使用粗体。如果你也这样做,现在会发生什么?
    • 哦,那是问题中的一个错误..屏幕截图来自 Fontstyle.Regular...问题保持不变...看起来这两个文本从彼此的文字越长..
    • @Salocin 我希望这是因为他们使用的绘图功能略有不同。特别是,DrawText() 可以使用 ClearType,但 AddString() 永远不会。
    • 哦..所以你的意思是没有解决问题的办法?
    猜你喜欢
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    相关资源
    最近更新 更多