如何:使用 GDI+ 呈现图像

可在应用程序中使用 GDI+ 呈现以文件形式存在的图像。 为此,可创建一个 Image 类的新对象(例如 Bitmap),创建一个引用要使用的绘图图面的 Graphics 对象,然后调用 Graphics 对象的 DrawImage 方法。 将在图形类所表示的绘图表面上绘制图像。 可在设计时使用图像编辑器创建和编辑图像文件,而在运行时使用 GDI+ 呈现图像。 有关详细信息,请参阅图标的图像编辑器

使用 GDI+ 呈现图像

  1. 创建一个对象,该对象表示要显示的图像。 此对象必须是继承自 Image(例如 BitmapMetafile)的类的成员。 下面显示了一个示例:

    ' Uses the System.Environment.GetFolderPath to get the path to the
    ' current user's MyPictures folder.  
    Dim myBitmap as New Bitmap _  
       (System.Environment.GetFolderPath _  
          (System.Environment.SpecialFolder.MyPictures))  
    
    // Uses the System.Environment.GetFolderPath to get the path to the
    // current user's MyPictures folder.  
    Bitmap myBitmap = new Bitmap  
       (System.Environment.GetFolderPath  
          (System.Environment.SpecialFolder.MyPictures));  
    
    // Uses the System.Environment.GetFolderPath to get the path to the
    // current user's MyPictures folder.  
    Bitmap^ myBitmap = gcnew Bitmap  
       (System::Environment::GetFolderPath  
          (System::Environment::SpecialFolder::MyPictures));  
    
  2. 创建一个 Graphics 对象,该对象表示要使用的绘图图面。 有关详细信息,请参阅如何:创建用于绘制的 Graphics 对象

    ' Creates a Graphics object that represents the drawing surface of
    ' Button1.  
    Dim g as Graphics = Button1.CreateGraphics  
    
    // Creates a Graphics object that represents the drawing surface of
    // Button1.  
    Graphics g = Button1.CreateGraphics();  
    
    // Creates a Graphics object that represents the drawing surface of
    // Button1.  
    Graphics^ g = button1->CreateGraphics();  
    
  3. 调用 Graphics 对象的 DrawImage 来呈现图像。 必须同时指定要绘制的图像以及将绘制它的位置坐标。

    g.DrawImage(myBitmap, 1, 1)  
    
    g.DrawImage(myBitmap, 1, 1);  
    
    g->DrawImage(myBitmap, 1, 1);  
    

另请参阅