画像をそのままのサイズで入力する

画像ファイルからそのままのサイズで入力して、サイズに合わせてウインドウを設定します。
既定値では、画像は2のベキ乗にサイズが調整されます。

プロジェクトの設定

  1. 空のプロジェクトを作成して、ソースプログラムをプロジェクトに取り込んで下さい。
    詳細は DirectX 3D で Form を表示 を参照して下さい。
    画像は適当なものを調達して下さい。
  2. Main() メソッドから呼ばれる CreateDevice Class です。
    device が DirectX の Device の定義です。
    Sprite が Sprite Object Class で device から生成します。
    texture が Texture Image Class で、ここに描画するイメージを読み込みます。
    ImgFile が入力する画像ファイルの名前です。
    width, height は入力する画像ファイルの幅と高さを格納する領域です。
        public class CreateDevice : Form
        {
            Device  device = null;          // Direct Device の定義
            Sprite  sprite = null;          // Sprite Object Class
            Texture texture;                // Texture Image
            string ImgFile = "c:\\data\\girl.bmp";
            int     width, height;
        
  3. Main() から呼ばれる DirectX Sprite の初期化を行う InitializeGraphics() です。
    new Device() で DirectX の Device を取得します。
    device が取得出来たら、続いて sprite を生成します。
    new Bitmap(ImgFile) で画像ファイルを入力して幅と高さを取得します。
    用済みの bmp を Dispose(); で開放します。
    WriteLine() で幅と高さを印字してみました。
    new System.Drawing.Size(width, height); で画像サイズに合わせてウインドウのサイズを設定します。
    FromFile() で texture に画像を入力します。
    幅と高さを指定すると、そのサイズで画像が入力されます。
    unchecked((int)0xFF000000) は透明色の設定で、黒を透明色に設定しています。
    透明色は int 型ですが、16進数をこのままキャストするとオーバーフローが生じます。
    unchecked() はオーバーフローを無視してコンパイルすることを指示します。
    透明色を使った描画は 透明色を使う を参照して下さい。
        public bool InitializeGraphics()
        {
            try
            {
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed=true;
                presentParams.SwapEffect = SwapEffect.Discard;
                device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
                sprite = new Sprite(device);
                //Image File をロードしてサイズを取得
                Bitmap  bmp= new Bitmap(ImgFile);
                width = bmp.Width;
                height = bmp.Height;
                bmp.Dispose();
                Console.WriteLine("Width={0}, Height={1}", width, height);
                ClientSize = new System.Drawing.Size(width, height);
                texture = TextureLoader.FromFile(device, ImgFile, width, height, 0,
                          Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.None, Filter.None, unchecked((int)0xFF000000));
                return true;
            }
            catch (DirectXException)
            {
                return false; 
            }
        }
        

【演習】

プログラムを完成させて下さい。

超初心者のプログラム入門(C# Frame Work)