2009-08-05 9 views
12

Parfois, les messages d'exception de Microsoft sont inefficaces. J'ai créé une belle petite méthode MVC pour rendre le texte. Le corps de la méthode est ci-dessous. Quand il atteint la méthode "DrawString", je reçois une exception disant "Parameter is not valid". Notez que la police, comme je peux le dire, est construite correctement (je n'utilise que Arial à 10pt), la taille rectale est positive et valide, le pinceau est un SolidBrush blanc et les drapeaux de format n'affectent pas la sortie, à savoir si j'Excluez les drapeaux de format de l'appel, je reçois encore une erreurSystem.Drawing.Graphics.DrawString - Exception "Parameter is not valid"

l'appel DrawString est juste à côté du fond

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

Juste une remarque: nouvelle SolidBrush (fc) fuiront une ressource pinceau, il a besoin d'un bloc à l'aide aussi. –

+1

Juste un conseil: j'ai eu la même erreur "Paramètre n'est pas valide" et est arrivé sur ce fil. Dans mon cas cela n'avait rien à voir avec la réponse acceptée, c'était parce que je passais à DrawString une instance Disposed de police ou de pinceau. L'exception n'est pas vraiment utile ... – AFract

Répondre

14

Eh bien, je trouve la cause du problème... Quelque chose de très obscur Le code fonctionne quand je supprime cette ligne:

gfx.CompositingMode = CompositingMode.SourceCopy; 
+0

Life Saver! Cela a du sens en fait, je suis sûr qu'il faut que le mélange soit activé pour dessiner du texte mais ce serait bien si le message d'erreur mentionnait quelque chose à ce sujet :-) – eodabash

4

Ce qui pourrait aider pendant le débogage, rend les méthodes plus petites. Par exemple, vous pouvez remplacer

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

par

FontStyle style = GetFontStyle(isBold, isItalic); 

et

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

Il rend votre code plus lisible et il le rend plus facile pour les autres pour vous aider.

Vraiment, pas d'offense!

Cordialement, Vlug

Ans
Questions connexes