C# System.Drawing.Graphics.DrawString-“;参数无效";例外

C# System.Drawing.Graphics.DrawString-“;参数无效";例外,c#,.net,gdi+,C#,.net,Gdi+,有时,微软的异常消息令人恼火地毫无用处。我创建了一个漂亮的MVC方法来渲染文本。方法主体如下所示。当它到达“DrawString”方法时,会抛出一个异常,说“参数无效” 请注意,正如我所知,字体的构造是正确的(我只是使用10磅的Arial),矩形大小是正的,看起来有效,画笔是白色的SolidBrush,格式标志不影响输出;也就是说,如果我从调用中排除格式标志,我仍然会得到一个错误 抽绳调用就在底部附近 public ActionResult RenderText( string font

有时,微软的异常消息令人恼火地毫无用处。我创建了一个漂亮的MVC方法来渲染文本。方法主体如下所示。当它到达“DrawString”方法时,会抛出一个异常,说“参数无效”

请注意,正如我所知,字体的构造是正确的(我只是使用10磅的Arial),矩形大小是正的,看起来有效,画笔是白色的SolidBrush,格式标志不影响输出;也就是说,如果我从调用中排除格式标志,我仍然会得到一个错误

抽绳调用就在底部附近

public ActionResult RenderText(
    string fontFamily,
    float pointSize,
    string foreColor,
    string backColor,
    bool isBold,
    bool isItalic,
    bool isVertical,
    string align,
    string[] allText,
    int textIndex)
{
    // method renders a horizontal or vertical text image, taking all the text strings that will be rendered in each image
    // and sizing the final bitmap according to which text would take the most space, thereby making it possible to render
    // a selection of text images all at the same size.

    Response.ContentType = "image/png";

    var fmt = StringFormat.GenericTypographic;
    if(isVertical)
        fmt.FormatFlags = StringFormatFlags.DirectionVertical;

    Func<string,StringAlignment> getAlign = (s => {
        switch(s.ToLower())
        {
            case "right": return StringAlignment.Far;
            case "center": return StringAlignment.Center;
            default: return StringAlignment.Near;
        }
    });
    fmt.LineAlignment = isVertical ? StringAlignment.Center : getAlign(align);
    fmt.Alignment = isVertical ? getAlign(align) : StringAlignment.Center;

    var strings = (allText ?? new string[0]).Where(t => t.Length > 0).ToList();
    if(strings.Count == 0)
        strings.Add("[Missing Text]");

    FontStyle style = FontStyle.Regular;
    if(isBold)
        if(isItalic)
            style = FontStyle.Bold | FontStyle.Italic;
        else
            style = FontStyle.Bold;
    else if(isItalic)
        style = FontStyle.Italic;

    Font font = new Font(fontFamily, pointSize, style, GraphicsUnit.Point);
    Color fc = foreColor.IsHexColorString() ? foreColor.ToColorFromHex() : foreColor.ToColor();
    Color bc = backColor.IsHexColorString() ? backColor.ToColorFromHex() : backColor.ToColor();

    var maxSize = new Size(0,0);
    using(var tmp = new Bitmap(100, 200))
        using(var gfx = Graphics.FromImage(tmp))
            foreach(var txt in strings)
            {
                var size = gfx.MeasureString(txt, font, 1000, fmt);
                maxSize = new Size(
                    Math.Max(Convert.ToInt32(isVertical ? size.Height : size.Width), maxSize.Width),
                    Math.Max(Convert.ToInt32(isVertical ? size.Width : size.Height), maxSize.Width)
                );
            }

    using(var bmp = new Bitmap(maxSize.Width, maxSize.Height))
    {
        using(var gfx = Graphics.FromImage(bmp))
        {
            gfx.CompositingMode = CompositingMode.SourceCopy;
            gfx.CompositingQuality = CompositingQuality.HighQuality;
            gfx.SmoothingMode = SmoothingMode.HighQuality;
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var rect = new RectangleF(new PointF(0,0), maxSize);
            gfx.FillRectangle(new SolidBrush(bc), rect);
            gfx.DrawString(strings[textIndex], font, new SolidBrush(fc), rect, fmt);
        }
        bmp.Save(Response.OutputStream, ImageFormat.Png);
    }
    return new EmptyResult();
}
public ActionResult RenderText(
这是我的家庭,
浮点大小,
弦前景色,
字符串背景色,
布尔·伊斯波尔德,
布尔·伊斯塔利克,
布尔是垂直的,
字符串对齐,
字符串[]所有文本,
int文本索引)
{
//方法渲染水平或垂直文本图像,获取将在每个图像中渲染的所有文本字符串
//并根据占用空间最大的文本调整最终位图的大小,从而使渲染成为可能
//所有大小相同的文本图像的选择。
Response.ContentType=“image/png”;
var fmt=StringFormat.GenericTyphographic;
如果(垂直)
fmt.FormatFlags=StringFormatFlags.DirectionVertical;
Func getAlign=(s=>{
开关(s.ToLower())
{
案例“右”:返回StringAlignment.Far;
案例“中心”:返回字符串对齐。中心;
默认值:返回StringAlignment.Near;
}
});
fmt.LineAlignment=isVertical?StringAlignment.Center:getAlign(align);
fmt.Alignment=isVertical?getAlign(align):StringAlignment.Center;
var strings=(allText??新字符串[0])。其中(t=>t.Length>0)。ToList();
if(strings.Count==0)
字符串。添加(“[缺少文本]”);
FontStyle=FontStyle.Regular;
如果(以粗体显示)
如果(伊斯兰语)
style=FontStyle.Bold | FontStyle.Italic;
其他的
style=FontStyle.Bold;
else if(伊斯兰语)
style=FontStyle.Italic;
Font Font=新字体(fontFamily、pointSize、style、GraphicsUnit.Point);
Color fc=foreColor.IsHexColorString()?foreColor.ToColorFromHex():foreColor.ToColor();
Color bc=backColor.IsHexColorString()?backColor.ToColorFromHex():backColor.ToColor();
var maxSize=新大小(0,0);
使用(var tmp=新位图(100200))
使用(var gfx=Graphics.FromImage(tmp))
foreach(字符串中的var txt)
{
var size=gfx.MeasureString(txt,字体,1000,fmt);
maxSize=新尺寸(
Math.Max(转换为32(isVertical?尺寸。高度:尺寸。宽度),maxSize。宽度),
Max(转换为32(isVertical?size.Width:size.Height)、maxSize.Width)
);
}
使用(var bmp=新位图(maxSize.Width、maxSize.Height))
{
使用(var gfx=Graphics.FromImage(bmp))
{
gfx.CompositingMode=CompositingMode.SourceCopy;
gfx.CompositingQuality=CompositingQuality.HighQuality;
gfx.SmoothingMode=SmoothingMode.HighQuality;
gfx.InterpolationMode=InterpolationMode.HighQualityBicubic;
var rect=new RectangleF(new PointF(0,0),maxSize);
FillRectangle(新的SolidBrush(bc),rect);
gfx.DrawString(字符串[textIndex],字体,新的SolidBrush(fc),rect,fmt);
}
保存(Response.OutputStream,ImageFormat.Png);
}
返回新的EmptyResult();
}

我找到了问题的原因。一些非常模糊的东西。当我删除这一行时,代码会起作用:

gfx.CompositingMode = CompositingMode.SourceCopy;

在调试过程中,可以帮助您缩小方法

FontStyle style = FontStyle.Regular;
if(isBold)
    if(isItalic)
        style = FontStyle.Bold | FontStyle.Italic;
    else
        style = FontStyle.Bold;
else if(isItalic)
    style = FontStyle.Italic;

它使您的代码更具可读性,也使其他人更容易帮助您

真的没有冒犯的意思

亲切问候,,
Ans Vlug

注意:新的SolidBrush(fc)将泄漏一个笔刷资源,它也需要一个using块。注意:我有相同的错误”参数无效“就这样到达了。在我的例子中,这与接受的答案无关,因为我正在向DrawString传递一个已处理的font或brush实例。例外情况并没有真正的帮助…救命!这是有道理的,事实上,我确信它需要启用混合来绘制文本,但如果错误消息中提到了这一点,那就太好了:-)
FontStyle style = GetFontStyle(isBold, isItalic);
public FontStyle GetFontStyle(bool isBold, bool isItalic)
{
    if(isBold)
        if(isItalic)
            return FontStyle.Bold | FontStyle.Italic;
        else
            return FontStyle.Bold;
    else if(isItalic)
        return FontStyle.Italic;
    else
        return FontStyle.Regular;
}