2014-01-08 42 views
0

我在用C#編寫的方法中呈現一些位圖。在DrawText方法中當前上下文錯誤下不存在名稱「e」

我正在學習使用TextRenderer.DrawText()方法將文本繪製到位圖上。該片段如下:

TextRenderer.DrawText(e.Graphics, "Regular Text", SystemFonts.DefaultFont, new Point(10, 10), SystemColors.ControlText);

然而,e.Graphics下,我給出的錯誤The name "e" does not exist under the current context

我想知道可能是什麼問題?

從我的渲染方法中的代碼段,通過Rhino-通用庫:

protected override void Render(Grasshopper.GUI.Canvas.GH_Canvas canvas, Graphics graphics, Grasshopper.GUI.Canvas.GH_CanvasChannel channel) { 
     base.Render(canvas, graphics, channel); 

     if (channel == Grasshopper.GUI.Canvas.GH_CanvasChannel.Wires) { 
      var comp = Owner as KT_HeatmapComponent; 
      if (comp == null) 
       return; 

      List<HeatMap> maps = comp.CachedHeatmaps; 
      if (maps == null) 
       return; 

      if (maps.Count == 0) 
       return; 

      int x = Convert.ToInt32(Bounds.X + Bounds.Width/2); 
      int y = Convert.ToInt32(Bounds.Bottom + 10); 

      for (int i = 0; i < maps.Count; i++) { 
       Bitmap image = maps[i].Image; 
       if (image == null) 
        continue; 

       Rectangle mapBounds = new Rectangle(x, y, maps[i].Width, maps[i].Height); 
       mapBounds.X -= mapBounds.Width/2; 

       Rectangle edgeBounds = mapBounds; 
       edgeBounds.Inflate(4, 4); 

       GH_Capsule capsule = GH_Capsule.CreateCapsule(edgeBounds, GH_Palette.Normal); 
       capsule.Render(graphics, Selected, false, false); 
       capsule.Dispose(); 

       graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; 
       graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; 
       graphics.DrawImage(image, mapBounds); 
       graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
       graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Default; 
       graphics.DrawRectangle(Pens.Black, mapBounds); 
       TextRenderer.DrawText(e.Graphics, "Regular Text", SystemFonts.DefaultFont, new Point(10, 10), SystemColors.ControlText); 

       y = edgeBounds.Bottom - (mapBounds.Height) - 4; 
      } 
     } 
    } 

上面的代碼段呈現熱圖到蚱蜢畫布,像這樣:

enter image description here

不過,我有興趣在其上添加標題和x/y軸文本。

+4

那麼您希望*'e'來自哪裏?我們在這裏沒有語境 - 這是在事件處理程序中嗎?還有別的嗎? –

+0

可能這段代碼來自一個繪製處理程序,並且傳遞了一個名爲'e'的事件對象。 –

+0

我剛剛得知這是一個事件處理程序arg。不,這不是一個事件處理程序,所以我可能會使用錯誤的方法在我的位圖上繪製文本。在編輯中我會更具體些。 – theGreenCabbage

回答

3

你已經發布的代碼看起來像它的設計是一個Paint事件處理程序中(因爲e是慣用的變量名稱爲事件處理程序的適當類型的EventArgsGraphicsPaintEventArgs屬性)。

既然你傳遞一個Graphics對象已經,你應該能夠與graphics參數代碼段來代替e.Graphics被傳遞到您的Render功能。您可以將此行添加到該功能:

TextRenderer.DrawText(graphics, "Regular Text", SystemFonts.DefaultFont, new Point(10, 10), SystemColors.ControlText); 
+0

'圖形'已經作爲參數傳入。無需使用'CreateGraphics()' – LarsTech

+0

如果我已經在上面聲明瞭'graphics',我該怎麼辦? – theGreenCabbage

+0

@LarsTech:這是在添加函數體的問題編輯之前。最初發布的所有內容都是單個「TextRenderer」行。 –

相關問題