Dim dlgOpen As New OpenFileDialog 'フィルターを設定する dlgOpen.Filter = "ビットマップ(*.bmp)|*.bmp|" & _ "JPEG(*.jpg)|*.jpg|" & _ "GIF(*.gif)|*.gif|" & _ "PNG(*.png)|*.png" If dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then 'PictureBoxにイメージを読み込む PictureBox1.Image = Image.FromFile(dlgOpen.FileName) PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage End If
Private sPos As MouseEventArgs 'マウスのドラッグの開始点 Private ePos As MouseEventArgs 'マウスのドラッグの終了点 Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown If e.Button = MouseButtons.Left Then '開始点の取得 sPos = e ePos = e End If End Sub Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove 'マウスのドラッグで線を引く If e.Button = MouseButtons.Left Then Dim g As Graphics = PictureBox1.CreateGraphics() Dim BPen As New Pen(Color.Black, 1) BPen.DashStyle = Drawing2D.DashStyle.Dash '描いたの一旦消す(VB6.0の XorPen の代り) # ここがこのサンプルのミソ PictureBox1.Refresh() '消える描画でドラッグ中の四角形を描く g.DrawRectangle(BPen, sPos.X, sPos.Y, ePos.X - sPos.X, ePos.Y - sPos.Y) ePos = e 'マウスポインタの移動終了点を取得 g.Dispose() End If End Sub Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp If e.Button = MouseButtons.Left Then PictureBox1.Refresh() '最後の四角形を削除 Dim g As Graphics = PictureBox1.CreateGraphics() Dim BPen As New Pen(Color.Black, 1) BPen.DashStyle = Drawing2D.DashStyle.Dash '範囲確定の四角形を描く g.DrawRectangle(BPen, sPos.X, sPos.Y, ePos.X - sPos.X, ePos.Y - sPos.Y) g.Dispose() '-------------- 指定範囲の画像取得部分 ----------------- '四角形の範囲の画像を取得 Dim rect As New Rectangle(sPos.X, sPos.Y, ePos.X - sPos.X, ePos.Y - sPos.Y) '選択範囲が異常の場合表示処理をしない If (ePos.X - sPos.X) < 2 Or (ePos.Y - sPos.Y) < 2 Then Exit Sub End If 'PictureBox2 のサイズを切り取った画像のサイズに合せる Dim g2 As Graphics 'コピー元の PictureBox を指定の事 Dim bmp As Bitmap = New Bitmap(PictureBox1.Image) With PictureBox2 .Image = New Bitmap(ePos.X - sPos.X, ePos.Y - sPos.Y) .SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize g2 = Graphics.FromImage(.Image) End With '取得した画像を PictureBox2 に表示 g2.DrawImage(bmp, 0, 0, rect, GraphicsUnit.Pixel) bmp.Dispose() g2.Dispose() End If End Sub
g.DrawRectangle(BPen, sPos.X, sPos.Y, ePos.X - sPos.X, ePos.Y - sPos.Y)