我试图在不安全的上下文中使用位图,并且看到其中不稳定,例如,程序第一次运行但第二次失败。这是代码:
private static void RenderBitmap(Graphics g)
{
const int width = 150, height = 150;
using (Bitmap bmp = new Bitmap(width, height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
NativeMethods.RenderText(Graphics.FromImage(bmp).GetHdc(), bmpData.Scan0,
"This works only first time round", "Segoe", 10,
new RGBA(255, 0, 0, 255), width, height);
bmp.UnlockBits(bmpData);
g.DrawImage(bmp, new Rectangle(width, height, width, -height));
}
}
看到这不起作用,我有几个问题。RenderText
如果本机方法直接操作位图内存,我正在做的事情是否安全且正确?我HDC
从位图获取的方式是否正确,还是应该使用g
从绘图方法传递的参数?
我得到的错误是:
" System.AccessViolationException 未处理 Message="尝试读取或写入受保护的内存。这通常表明其他内存已损坏。"