このコードを実行するには、Visual Studio .NETでWindowsアプリケーションを新規作成し、ListBoxコントロールとButtonコントロールをフォームに配置しておく必要がある。そして、配置したButtonコントロールのClickイベント、ListBoxコントロールのDrawItemイベントとMeasureItemイベントの各イベント・ハンドラとして、リスト内の3つのメソッドをそのコメントに従って指定しておく。
const int spacing = 3; // 画像の周りの余白
const int MaxItemHeight = 255; // ItemHeightの最大値
foreach (string s in images)
{
Image original = Image.FromFile(s);
Image thumbnail = createThumbnail(
original,
listBox1.ClientSize.Width - spacing * 2,
MaxItemHeight - spacing * 2);
listBox1.Items.Add(thumbnail); // 画像の追加
original.Dispose();
// thumbnailオブジェクトは破棄できない
}
}
Const spacing As Integer = 3 ' 画像の周りのスペース
Const MaxItemHeight As Integer = 255 ' ItemHeightの最大値
' 幅w、高さh内に収まるようなImageオブジェクトを作成
Function createThumbnail(ByVal image As Image, ByVal w As Integer, ByVal h As Integer) As Image
Dim fw As Double = CDbl(w) / CDbl(image.Width)
Dim fh As Double = CDbl(h) / CDbl(image.Height)
Dim scale As Double = Math.Min(fw, fh)
Dim nw As Integer = CInt(image.Width * scale)
Dim nh As Integer = CInt(image.Height * scale)
Return New Bitmap(image, nw, nh)
End Function
' ListBoxのDrawItemイベントのハンドラ
Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem
If e.Index = -1 Then ' 項目がない場合にも呼び出される
Return
End If
' ListBoxのMeasureItemイベントのハンドラ
Private Sub ListBox1_MeasureItem(ByVal sender As Object, ByVal e As MeasureItemEventArgs) Handles ListBox1.MeasureItem
Dim thumbnail As Image = CType(ListBox1.Items(e.Index), Image)
e.ItemHeight = thumbnail.Height + spacing * 2
End Sub
' ButtonのClickイベントのハンドラ
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' プロパティ設定
ListBox1.ScrollAlwaysVisible = True
ListBox1.DrawMode = DrawMode.OwnerDrawVariable
Dim imageDir As String = "c:\images" ' 画像ディレクトリ
Dim images As String() = System.IO.Directory.GetFiles(imageDir, "*.jpg")
For Each s As String In images
Dim original As Image = Image.FromFile(s)
Dim thumbnail = createThumbnail(original, _
ListBox1.ClientSize.Width - spacing * 2, _
MaxItemHeight - spacing * 2)
ListBox1.Items.Add(thumbnail) ' 画像の追加
original.Dispose()
' thumbnailオブジェクトは破棄できない
Next
End Sub