.NETでpictureBoxに四角を描画するプログラムを作成しています。
行いたいこと
・pictureBoxにマウスで(Btndown→drag→BtnUp)の操作で四角を描画
・もう一度描画しようとしてBtndownすると前に描画したものが消えて新しく四角を描画
以上の動作をさせたいです。しかし、現状は四角が消えずに何個も描画できてしまう状態です。
以下に記載しているプログラムはこちらのサイトの「マウスをなぞった位置にリアルタイムに四角形を描画し、マウスを離すとその位置に四角形を追加する」
というプログラムの不要な機能を取り除いたものになります。
コピーしてきたプログラムなので理解して希望通りの動作をさせようと以下のことを試しました。
試したこと
コレクションに描画した四角を格納し、それらを描画しているようなので、二回四角を描画した場合は一回目の四角を消すために、RemoveAtメソッドをつかってコレクションの初期化を行うということを
しました。しかし、思うように動作せず苦戦しています。
ということですが、以下のプログラムを希望通りの動作をさせるためにはどのように修正すべきでしょうか。ご教示願います。
Public Class Form1 Private paths As New List(Of Drawing2D.GraphicsPath) Private mouseDownPosition As Point 'ドラッグを開始したマウスの位置 Private mouseDragPosition As Point '現在ドラッグ中のマウスの位置 Private isMouseDown As Boolean 'マウスのボタンが押されているか Private selectPen As Pen 'ドラッグ中の四角形の描画 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'ドラッグ中の四角形の描画に使用するペンを作成。黄色のペンにする。 selectPen = New Pen(Color.Yellow, 1) selectPen.DashStyle = Drawing2D.DashStyle.Solid End Sub Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint '追加されている図形を描画する。 For Each path In paths e.Graphics.DrawPath(Pens.Yellow, path) '黄色い枠線 Next If Control.MouseButtons <> MouseButtons.Left Then 'マウスの左ボタンが押されていない場合何もしない Return End If 'ドラッグを開始したマウスの位置(mouseDownPosition)と現在ドラッグ中のマウスの位置(mouseDragPosition) 'から、描画すべき四角形の座標を計算する。 Dim activeRect As Rectangle = CalcActiveRect(mouseDownPosition, mouseDragPosition) 'ドラッグ中の四角形を描画 e.Graphics.DrawRectangle(selectPen, activeRect) End Sub Private Function CalcActiveRect(startPosition As Point, endPosition As Point) As Rectangle Dim activeRect As New Rectangle activeRect.X = Math.Min(mouseDownPosition.X, mouseDragPosition.X) activeRect.Y = Math.Min(mouseDownPosition.Y, mouseDragPosition.Y) activeRect.Width = Math.Abs(mouseDragPosition.X - mouseDownPosition.X) activeRect.Height = Math.Abs(mouseDragPosition.Y - mouseDownPosition.Y) Return activeRect End Function Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown 'マウスのボタンが押された場合 mouseDownPosition = e.Location isMouseDown = True End Sub Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove 'マウスを移動した場合 mouseDragPosition = e.Location PictureBox1.Invalidate() 'PictureBoxを強制的に再描画する End Sub Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseUp 'マウスを離した場合 If isMouseDown = True Then Dim activeRect As Rectangle = Me.CalcActiveRect(mouseDownPosition, mouseDragPosition) If activeRect.Width * activeRect.Height > 0 Then '面積がある場合、この四角形を描画対象に追加する。 Dim path As New Drawing2D.GraphicsPath() path.AddRectangle(activeRect) paths.Add(path) End If isMouseDown = False End If PictureBox1.Invalidate() 'PictureBoxを強制的に再描画する End Sub
バージョン
Microsoft Visual Studio Community 2022 Version 17.2.2
Windows フォームアプリを.NET Framework 4.7.2で作成しています。
回答1件
あなたの回答
tips
プレビュー