System.Drawing.Graphics.DrawString - "Parameter is not valid"异常

17
有时候,微软的异常消息让人非常恼火。我创建了一个很好的MVC方法来呈现文本。该方法的主体如下。当它到达“DrawString”方法时,我会收到一个抛出的异常,提示“参数无效”。
请注意,字体(据我所知只是使用10pt Arial),矩形大小是正面有效的,刷子是白色的SolidBrush,格式标志不影响输出;即使我从调用中排除格式标志,我仍然会得到错误。
DrawString调用就在底部附近。
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();
}

1
只是一个提示:new SolidBrush(fc) 会泄漏 Brush 资源,它也需要使用 using 块。 - H H
2
只是一个提示:我遇到了相同的错误“参数无效”,并进入了这个线程。在我的情况下,它与接受的答案无关,而是因为我正在传递一个已释放的字体或画刷实例给DrawString。异常并没有真正有用... - AFract
2个回答

25

我找到了问题的原因。非常奇怪。当我删除这行代码时,程序可以正常运行:

gfx.CompositingMode = CompositingMode.SourceCopy;

真是救命稻草!这其实很有道理,我相信需要启用混合才能绘制文本,但如果错误消息提到了这一点会更好 :-) - eodabash

4

在调试时有助于的一点是,将方法变得更小。比如,您可以替换掉

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

通过

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;
}

它能使你的代码更易读,也能让别人更容易地帮助你。

真的没有冒犯之意!

祝好, Ans Vlug


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接