我想创建一个Picturebox,使其形状适应某个Font的字符串。我需要这个,以便以后可以创建文本并将其放在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或反之?
这就是它的样子:
答案 0 :(得分: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
。