ビットマップ画像の解像度をディスプレイの解像度に合わせて画面に描画する - C#

ビットマップの画像をDrawImageメソッドなどで画面に描画すると意図したサイズより拡大、または縮小されて描画されることがあります(参考記事)。これは.NET Frameworkではビットマップ画像を画面に描画する際にビットマップファイルの解像度を参照するためです。この記事では、ビットマップの画像解像度をディスプレイの画像解像度に合わせて描画し画像の拡大や縮小を防ぐ方法を紹介します。

画像の作成

下図の画像を作成します。画像のサイズは64×64Pixel 72dpi で作成します。


作成した画像をプロジェクトに追加します。追加後ソリューションエクスプローラで画像ファイルを選択し、[プロパティ]の[出力ディレクトリにコピー]を"常にコピーする"に変更します。

画像が拡大されてるコード

以下のコードを実装します。
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.Runtime.InteropServices;

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

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      Bitmap bmp = new Bitmap("ball.bmp");
     
      Graphics g = System.Drawing.Graphics.FromImage(bmp);
      IntPtr bmpdc = g.GetHdc();

      e.Graphics.DrawImage(bmp, new Point(20, 70));
    }
  }
}

実行結果

このプログラムを実行すると、下図の画面が表示されます。意図していた画像のサイズより大きく表示されています。


画像の解像度をディスプレイの解像度に合わせる

以下のコードを記述すると画像の解像度をディスプレイの解像度に合わせてから画像を描画します。
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.Runtime.InteropServices;

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

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      Bitmap bmp = new Bitmap("ball.bmp");
     
      Graphics FormG = this.CreateGraphics();
      bmp.SetResolution(FormG.DpiX, FormG.DpiY);

      Graphics g = System.Drawing.Graphics.FromImage(bmp);
      IntPtr bmpdc = g.GetHdc();

      e.Graphics.DrawImage(bmp, new Point(20, 70));
    }
  }
}

解説

Graphics FormG = this.CreateGraphics();
にて、アプリケーションのウィンドウのグラフィックスオブジェクトを作成します。グラフィックスオブジェクトのDpiX,DpiYから解像度が取得できます。この値がディスプレイの解像度になります。

bmp.SetResolution(FormG.DpiX, FormG.DpiY);
にて画像の解像度をディスプレイの解像度に設定します。解像度設定後に画面に画像を描画します。

実行結果

このプログラムを実行すると、下図の画面が表示されます。


参考

OnPaintイベント以外(Graphicsオブジェクトが引数として与えられない場合)では、以下のコードで描画ができます。
    private void button1_Click(object sender, EventArgs e)
    {
      Bitmap bmp = new Bitmap("ball.bmp");

      Graphics gw = System.Drawing.Graphics.FromHwnd(this.Handle);
      IntPtr hdc = gw.GetHdc();
      IntPtr hsrc = CreateCompatibleDC(hdc);
      IntPtr porg = SelectObject(hsrc, bmp.GetHbitmap());

      BitBlt(hdc, 20, 80, bmp.Width, bmp.Height, hsrc, 0, 0, TernaryRasterOperations.SRCCOPY);

      DeleteDC(hsrc);
      gw.ReleaseHdc(hdc);
    }
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-01-29
iPentec all rights reserverd.