我需要创建一支笔,无论图形转换矩阵的比例如何,都能以0.5毫米的宽度绘制。这是我的做法:
注意:示例代码为C++/CLI,但使用C#回答也可以。
// assume that g is a Graphics object
int dpi = g->DpiX;
float dotsPerHalfInch = dpi * 0.5;
// to extract scale factor from the transformation matrix...
// create two points distant one unit apart...
array<PointF> ^points = gcnew array<PointF>{
PointF(0.0f, 0.0f), PointF(1.0f, 0.0f)
};
// transform them...
g->Transform->TransformPoints(points);
// get distance after transformation...
float dX = points[1].X - points[0].X;
float dY = points[1].Y - points[0].Y;
float distance = Math::Sqrt(dX * dX + dY * dY);
// reverse the effects of any scale factor in graphics transform
float penWidth = dotsPerHalfInch / distance;
Pen ^halfInchPen = gcnew Pen(Color::Black, penWidth);
在屏幕上(96 dpi)似乎不起作用...给我一支像素宽的笔。在 PDF 打印机(600 dpi)上,它给了我一支比半英寸更粗的笔。
我做错了什么?在 GDI 中创建非缩放笔的正确方法是什么?