缓存设备上下文

时间:2019-05-03 15:04:36

标签: c# windows gdi+

要绘制一些文字,我使用

Size GetStringSize(LOGFONT logFont, string stringToMeasure)
{
     Font font = FontCache.Default.GetOrCreate(logFont);
     using(var graphics = System.Drawing.Graphics.FromHwnd(Display.HWND))
     {
        return TextRenderer.MeasureText(graphics, stringToMeasure, font, new Size(1000000, 1000000));
     }
}

我可以毫无问题地缓存字体对象。但是我不确定是否可以缓存 Graphics 对象,或者是否可以通过将null传递给 FromHWnd 来简单地使用当前显示的 Graphics 对象 em>?

性能问题很真实:

Line #, Process, Stack Tag, Stack - (Callees of System.Drawing.ni.dll!System.Drawing.Graphics.FromHwnd(IntPtr)), Weight (in view) (ms)
7, ,   |  , System.Drawing.ni.dll!System.Drawing.Graphics.FromHwnd(IntPtr), 21,334.418715
8, ,   |  ,   |- System.Drawing.ni.dll!System.Drawing.Graphics.FromHwndInternal(IntPtr), 21,304.413686
9, ,   |  ,   |    |- System.Drawing.ni.dll!DomainBoundILStubClass.IL_STUB_PInvoke(System.Runtime.InteropServices.HandleRef, System.Drawing.FontStyle, Int32 ByRef), 21,264.422130
10, ,   |  ,   |    |    |- GdiPlus.dll!GdipCreateFromHWND, 21,244.429337
11, ,   |  ,   |    |    |    |- GdiPlus.dll!GpGraphics::GetFromHwnd, 21,214.423913
12, ,   |  ,   |    |    |    |    |- GdiPlus.dll!GpGraphics::GpGraphics, 20,824.349264
13, ,   |  ,   |    |    |    |    |    |- win32u.dll!ZwUserGetDC, 20,042.878233
14, ,   |  ,   |    |    |    |    |    |    |- ntoskrnl.exe!KiSystemServiceCopyEnd, 19,952.862751
15, ,   |  ,   |    |    |    |    |    |    |    win32kbase.sys!NtUserGetDC, 19,952.862751
16, ,   |  ,   |    |    |    |    |    |    |    |- win32kbase.sys!_GetDCEx, 19,842.849739
17, ,   |  ,   |    |    |    |    |    |    |    |    |- win32kbase.sys!HmgShareLock, 7,384.475206
18, ,   |  ,   |    |    |    |    |    |    |    |    |    |- win32kbase.sys!HANDLELOCK::vLockHandle, 3,085.609601
19, ,   |  ,   |    |    |    |    |    |    |    |    |    |    |- ntoskrnl.exe!ExAcquirePushLockExclusiveEx, 2,154.100038
20, ,   |  ,   |    |    |    |    |    |    |    |    |    |    |    |- ntoskrnl.exe!ExAcquirePushLockExclusiveEx<itself>, 1,984.037148

我在那里花了21秒钟,这很多。这离ns很远。大约有4个线程同时执行此操作以加快绘图速度。

什么会使缓存的 Graphics 对象失效?在这种情况下,我不会画任何东西来仅测量文本大小,因此应该非常容易缓存。字体指定为负高度,表示以像素为单位声明。

0 个答案:

没有答案
相关问题