|
■No62347 (森のゴリラ さん) に返信
> PictureBoxに表示させている画像の任意の領域を選択し、例えばその領域の画像の抜き取りや
> トリミングなどを行いたいです。
Public Class Form1
Private Dragging As Boolean
Private requireClip As Boolean = False
Private MousePos1, MousePos2 As Point
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseDown
Dragging = True
MousePos1 = PictureBox1.PointToClient(MousePosition)
PictureBox1.Invalidate()
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
PictureBox1.Invalidate()
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseUp
requireClip = True
PictureBox1.Refresh()
Dragging = False
requireClip = False
End Sub
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles PictureBox1.Paint
If Dragging Then
MousePos2 = PictureBox1.PointToClient(MousePosition)
Dim DragArea As New Rectangle( _
Math.Min(MousePos1.X, MousePos2.X), _
Math.Min(MousePos1.Y, MousePos2.Y), _
Math.Abs(MousePos1.X - MousePos2.X), _
Math.Abs(MousePos1.Y - MousePos2.Y))
If DragArea.Width > 0 AndAlso DragArea.Height > 0 Then
If Not requireClip Then
ControlPaint.DrawFocusRectangle(e.Graphics, DragArea)
Else
Dim bmp As New Bitmap(DragArea.Width, DragArea.Height)
Using g As Graphics = Graphics.FromImage(bmp)
Dim img As Image = If(PictureBox1.Image, PictureBox1.BackgroundImage)
If img Is Nothing Then
g.Clear(PictureBox1.BackColor)
Else
g.DrawImage(img, New Rectangle(Point.Empty, bmp.Size), DragArea, GraphicsUnit.Pixel)
End If
End Using
PictureBox2.Image = bmp
End If
End If
End If
End Sub
End Class
|