对图元文件使用Graphic.DrawLines(钢笔,点数),当点数大时图片无法打开

时间:2014-02-17 23:16:40

标签: c# gdi+ metafile

我的GDI +图元文件有问题。我想通过图形保存图元文件。当点数为10000并且可以打开保存的元文件时,它可以正常工作。但是当点数很大(例如count = 10000000)时,mspaint.exe无法打开图元文件。

我错过了什么吗?元文件记录大小是否有限?顺便说一句,drawrectangles也有这个问题。

这是我的代码:

private void button1_Click(object sender, EventArgs e)  
{  
    int width = 1489;  
    int height = 471;

    Graphics offScreenBufferGraphics;
    Metafile m;
    using (MemoryStream stream = new MemoryStream())
    {
        using (offScreenBufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
        {
            IntPtr deviceContextHandle = offScreenBufferGraphics.GetHdc();
            m = new Metafile(
            stream,
            deviceContextHandle,
            new RectangleF(0, 0, width, height),
            MetafileFrameUnit.Pixel,
            EmfType.EmfPlusOnly);
            offScreenBufferGraphics.ReleaseHdc();
        }
    }

    using (Graphics g = Graphics.FromImage(m))
    {
        // Set everything to high quality
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        MetafileHeader metafileHeader = m.GetMetafileHeader();
        g.ScaleTransform(
            metafileHeader.DpiX / g.DpiX,
            metafileHeader.DpiY / g.DpiY);

        g.PageUnit = GraphicsUnit.Pixel;
        g.SetClip(new RectangleF(0, 0, width, height));

        // clears the image and colors the entire background
        g.Clear(Color.White);

        // draw lines
        using (Pen pen = new Pen(Color.Black, 1f))
        {
            Random rnd = new Random(DateTime.Now.Millisecond);
            List<PointF> polyPoints = new List<PointF>();
            const int count = 10000;
            for (int i = 1; i <= 10000000; i++)
            {
                polyPoints.Add(new PointF(rnd.Next(1000),rnd.Next(1000)));
            }
            g.DrawLines(pen, polyPoints.ToArray());
            // while
        } // using
    } // using

    // Get a handle to the metafile
    IntPtr iptrMetafileHandle = m.GetHenhmetafile();

    // Export metafile to an image file
    CopyEnhMetaFile(iptrMetafileHandle, @"F:\CacheToDisk\test2.emf");

    // Delete the metafile from memory
    DeleteEnhMetaFile(iptrMetafileHandle);
}

[DllImport("gdi32.dll")]
static extern IntPtr CopyEnhMetaFile(  // Copy EMF to file
    IntPtr hemfSrc,   // Handle to EMF
    String lpszFile // File
);

[DllImport("gdi32.dll")]
static extern int DeleteEnhMetaFile(  // Delete EMF
    IntPtr hemf // Handle to EMF
);

1 个答案:

答案 0 :(得分:0)

似乎是限制。如果我使用 DrawPath 而不是 DrawLines ,它可以正常工作。