开发者

DrawString and DrawRectangle using same X&Y start at different places

开发者 https://www.devze.com 2023-03-18 16:45 出处:网络
I have the following code: public void DrawLetter(int Cell, string Letter, int X, int Y) { System.Drawing.Font fBody = new System.Drawing.Font(\"Courier New\", 12F, System.Drawing.FontStyle.Regular,

I have the following code:

public void DrawLetter(int Cell, string Letter, int X, int Y)
{
   System.Drawing.Font fBody = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));

   Pencil.DrawString(Letter, fBody, System.Drawing.Brushes.Black, X, Y);
   Pencil.DrawRectangle(new Pen(System.Drawing.Brushes.Red), X, Y, 10, 10);        
}

When I go through this twice and use 140,249 and 296,249 as co-ordinates the rectangle appears as I would expect in the correct position but the string appears a few pixels out and I can't work out why.

I put in the DrawRectangle to check that it was starting in the correct position and it is. Am I doing something wrong in the DrawString? Also if I draw a D and a Z the width of the D is 10px and Z is 8px, I thought using Courier it would give me fixed width?

UPDATE: I looked at the sample on MSDN and here is a screenshot. Even though the DrawString is positioned at 0,0 you can see that the letter does not appear at 0,0. The rectangle does though. There must be padding or something:

DrawString and DrawRectangle using same X&Y start at different places

UPDATE 2: Using the following code seems to 开发者_开发知识库improve things although its not perfect:

StringFormat strFormat = new StringFormat(StringFormat.GenericTypographic);
Pencil.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
Pencil.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0), strFormat);

DrawString and DrawRectangle using same X&Y start at different places


It wouldn't be the default padding / line-height etc being taken into account for the "Courier New" font would it?

0

精彩评论

暂无评论...
验证码 换一张
取 消