yuanrui / blog

Some notes.
http://yuanrui.github.io
3 stars 0 forks source link

.Net图像开发填坑记录 #20

Open yuanrui opened 5 years ago

yuanrui commented 5 years ago

一段简单的代码,新建一个Bitmap对象,向其中绘制一些文字。

var targetBitmap = new Bitmap(500, 600);
using (var graphic = Graphics.FromImage(targetBitmap))
{
    graphic.CompositingMode = CompositingMode.SourceCopy;
    graphic.CompositingQuality = CompositingQuality.HighQuality;
    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

    String drawString = "TEST STRING";
    Font drawFont = new Font("Arial", 16);
    SolidBrush drawBrush = new SolidBrush(Color.Yellow);
    RectangleF drawRect = new RectangleF(0, 300, 500, 200);
    Pen blackPen = new Pen(Color.Black);
    graphic.DrawRectangle(blackPen, 0, 500, 600, 200);
    StringFormat drawFormat = new StringFormat();
    drawFormat.Alignment = StringAlignment.Far;
    graphic.DrawString(drawString, drawFont, drawBrush, drawRect, drawFormat);   
}

编译没有问题,走查代码也没有发现问题,但是运行就是会抛异常。异常提示参数无效。

System.ArgumentException
  HResult=0x80070057
  Message=参数无效。
  Source=System.Drawing
  StackTrace:
   at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
   at System.Drawing.Graphics.DrawString(String s, Font font, Brush brush, 
RectangleF layoutRectangle, StringFormat format)
   at Program.Main(String[] args) in ...

百思不得其解,后面通过删除代码的方式,逐行定位到问题所在,去掉设置CompositingMode就好了。