Web検索はbingがおすすめ!

ビットマップ画像を画面に描画する - C#

ビットマップ画像を画面に描画する方法を紹介します。

UI

下図のUIを準備します。新規作成状態から何も変更していません。

表示画像の準備

下図の画像を用意します。画像はプロジェクトに追加します。


ソリューションエクスプローラで画像のファイルを選択し、プロパティ画面を表示します。[ビルドアクション]プロパティを[埋め込まれたリソース]にします。

コード

以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;

namespace SimpleDrawImage
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      Assembly assembly = Assembly.GetExecutingAssembly();
      Stream stream = assembly.GetManifestResourceStream("SimpleDrawImage.ball.bmp");
      Bitmap bmp = new Bitmap(stream);

      bmp.SetResolution(e.Graphics.DpiX, e.Graphics.DpiY);

      e.Graphics.DrawImage(bmp, new Point(40, 80));
    }
  }
}

解説

Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("SimpleDrawImage.ball.bmp");
Bitmap bmp = new Bitmap(stream);
にて、リソースから画像を読み込みます。リソースの埋め込みや取得についてはこちらの記事を参照してください。

bmp.SetResolution(e.Graphics.DpiX, e.Graphics.DpiY);
ビットマップの画像の解像度とスクリーンの画像解像度を合わせています。詳細はこちらの記事を参照してください。

e.Graphics.DrawImage(bmp, new Point(40, 80));
フォームの(x,y)=(40,80)の位置に画像を描画します。

実行結果

アプリケーションを実行します。フォームに画像が描画され下図の結果が得られます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2023-12-28
作成日: 2012-02-03
iPentec all rights reserverd.