[WPF] ImageViewer

「ドラッグ&ドロップ」の秀作として、WPFでImageViewrを作ってみます。

作ってみるのは以下のようなアプリケーションです。ここにエクスプローラなどから画像ファイルをドロップすることでその画像を表示するアプリケーションを作成します。

 

 

[環境]

コンパイラ : Visual Studio 2012  
プラットフォーム: .NET Framework 4  

 

 

 

 


 

1. VS2012でWPF新規プロジェクトを作成

最初にVS2012でWPF新規プロジェクトを作成します。

 

 

2. 部品を配置、大きさを適当に修正

(1) Windowの大きさを適当に修正。ここでは、幅を 287、高さを 272 に設定。
(2) Grid の下に Border と Image を配置。後で使用するのでImageの名前を”Image01”と付けた。

 

 

3. 起動時の画面イメージを作成

起動時の画面であるメッセージ「ここに画像ファイルをドロップしてください。」をPNGファイルで作成し、Image01に表示します。
作成した画像は下図の通り。

 

これを Image01 の Source として設定し、Windowのタイトル()を”ImageViewer”と設定すると、以下のようなアプリケーションが起動するようになります。

 

これでとりあえずとっかかりまで完成。

 

 

4. Drag&Drop

いよいよ本題のDrag&Dropの実現方法になります。
以下の手順で進めます。
(1) Image01 の AllowDrop を有効にします。

(2) Image01 の Drop イベントを設定します。

 

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Image01_Drop(object sender, DragEventArgs e)
        {
            String[] files = e.Data.GetData(DataFormats.FileDrop) as string[];

            foreach (string filename in files)
            {
                System.Diagnostics.Trace.WriteLine(filename);
            }

            if (files.Length > 0)
            {
                try
                {
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;    // メモリリーク対策
                    bi.CreateOptions = BitmapCreateOptions.None;  // メモリリーク対策
                    bi.UriSource = new Uri(files[0]);
                    bi.EndInit();
                    bi.Freeze();                                  // メモリリーク対策
                    Image01.Stretch = Stretch.Uniform;
                    Image01.Source = bi;
                }
                catch (NotSupportedException)
                {
                    MessageBox.Show("ファイル\"" + files[0] + "\" はサポート外のファイルフォーマットです。", "ERRORメッセージ", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }

            e.Handled = true;
        }
    }

これで Bitmap,PNGなどのイメージファイルをドラッグ&ドロップすることで絵を表示するようになりました。

 

(3) DragOver イベント
最後にDragOverのイベント処理を追加します。アプリケーションにファイルをドロップしたときにマウスカーソルをコピー(+)のアイコンに変える処理です。
Image01のDragOverイベントを加えます。

 

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Image01_Drop(object sender, DragEventArgs e)
        {
            String[] files = e.Data.GetData(DataFormats.FileDrop) as string[];

            foreach (string filename in files)
            {
                System.Diagnostics.Trace.WriteLine(filename);
            }

            if (files.Length > 0)
            {
                try
                {
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;           // メモリリーク対策
                    bi. bi.CreateOptions = BitmapCreateOptions.None;     // メモリリーク対策
                    bi.UriSource = new Uri(files[0]);
                    bi.EndInit();
                    bi.Freeze();                                         // メモリリーク対策
                    Image01.Stretch = Stretch.Uniform;
                    Image01.Source = bi;
                }
                catch (NotSupportedException)
                {
                    MessageBox.Show("ファイル\"" + files[0] + "\" はサポート外のファイルフォーマットです。", "ERRORメッセージ", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }

            e.Handled = true;
        }

        private void Image01_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }
    }

以上で完成です。

 

サンプルプログラム ダウンロード

 


 

ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

  Copyright 2013 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

参考

 


 

変更履歴

2023-04-02 - ページデザイン刷新
2014-06-14 - BitmapImage のメモリリーク対策を追加
2013-08-18 - 新規作成

 

Programming Items トップページ

プライバシーポリシー