我在绘制自定义控件时使用缩放和转换我的图形对象,以便应用缩放和滚动。我使用以下内容:
Matrix mx = new Matrix();
mx.Scale(mZoomFactor, mZoomFactor);
mx.Translate(-clip.X + mGraphicsOffsetx, -clip.Y + mGraphicsOffsety);
e.Graphics.Clip = new Region(this.Bounds);
e.Graphics.Transform = mx;
然后当我使用:
绘制字符串时Graphics g = ...
g.DrawString(...)
scalling和transforming正确应用于字符串,它们被缩小和缩小等等。
但是,如果我使用以下内容来绘制我的字符串:
TextRenderer.DrawText(...)
文本未正确缩放和转换。
您知道如何将此概念应用于TextRenderer
吗?
答案 0 :(得分:6)
上述评论是准确的 - TextRenderer.DrawText
,作为GDI,由于其分辨率依赖性,对坐标转换的支持有限。正如您所注意到的那样,支持坐标转换,但不支持缩放(也不是坐标旋转)。
我们使用的解决方案(以及我能够在互联网上找到的唯一资源)是手动缩放Font
和Rectangle
个对象,以反映{Matrix.Scale(float, float)
应用的缩放比例1}}与Graphics.Transform
:
private Font GetScaledFont(Graphics g, Font f, float scale)
{
return new Font(f.FontFamily,
f.SizeInPoints * scale,
f.Style,
GraphicsUnit.Point,
f.GdiCharSet,
f.GdiVerticalFont);
}
private Rectangle GetScaledRect(Graphics g, Rectangle r, float scale)
{
return new Rectangle((int)Math.Ceiling(r.X * scale),
(int)Math.Ceiling(r.Y * scale),
(int)Math.Ceiling(r.Width * scale),
(int)Math.Ceiling(r.Height * scale));
}
以下是整个测试表格:
public partial class Form1 : Form
{
private PictureBox box = new PictureBox();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
public void Form1_Load(object sender, EventArgs e)
{
box.Dock = DockStyle.Fill;
box.BackColor = Color.White;
box.Paint += new PaintEventHandler(DrawTest);
this.Controls.Add(box);
}
public void DrawTest(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
string text = "Test Text";
float scale = 1.5F;
float translate = 200F;
var flags = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform;
var mx = new Matrix();
mx.Scale(scale, scale);
mx.Translate(translate, translate);
g.Clip = new Region(Bounds);
g.Transform = mx;
Size rendererPSize = Bounds.Size;
Font f = GetScaledFont(g, new Font("Arial", 12), scale);
Size rendererRSize = TextRenderer.MeasureText(g, text, f, rendererPSize, flags);
Rectangle rendererRect = new Rectangle(0, 0, rendererRSize.Width, rendererRSize.Height);
Rectangle r = GetScaledRect(g, rendererRect, scale);
TextRenderer.DrawText(g, text, f, realRect, Color.Black, flags);
}
private Font GetScaledFont(Graphics g, Font f, float scale)
{
return new Font(f.FontFamily,
f.SizeInPoints * scale,
f.Style,
GraphicsUnit.Point,
f.GdiCharSet,
f.GdiVerticalFont);
}
private Rectangle GetScaledRect(Graphics g, Rectangle r, float scale)
{
return new Rectangle((int)Math.Ceiling(r.X * scale),
(int)Math.Ceiling(r.Y * scale),
(int)Math.Ceiling(r.Width * scale),
(int)Math.Ceiling(r.Height * scale));
}
}