如何:使用 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. 创建一个表示你想要使用的绘图图面的对象。 有关详细信息,请参阅 “如何:为绘图创建图形对象”。

    ' 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. 调用图形对象的DrawImage方法来呈现图像。 必须同时指定要绘制的图像及其绘制位置的坐标。

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

另请参阅