Выделение участка изображения в PictureBox - Visual Basic .NET

Узнай цену своей работы

Формулировка задачи:

Привет всем! Хотел бы реализовать функцию, которая бы позволяла на изображении в PictureBox менять размер и положение участка выделения (прямоугольника) с помощью мыши, то есть, например, как в Paint или любом другом графическом редакторе. На изображении стоит прямоугольник и, тягая за его края, можно было бы менять размер этого прямоугольника. Рисование самого прямоугольника делаю так:
Листинг программы
  1. Dim g As Graphics
  2. Dim bmp As New Bitmap(PictureBox1.Image)
  3. g = Graphics.FromImage(bmp)
  4. Dim pen As New Pen(Color.Red, 3)
  5. g.DrawRectangle(pen, rect)
где

rect

- это тип Rectangle, определяющий его границы. Как можно мышь к прямоугольнику привязать, чтобы менять его размеры, подскажите, пожалуйста? Спасибо!

Решение задачи: «Выделение участка изображения в PictureBox»

textual
Листинг программы
  1. Public Class RubberBand
  2.     ' ----- The three types of rubber bands.
  3.     Public Enum RubberBandStyle
  4.         DashedLine
  5.         ThickLine
  6.         SolidBox
  7.         SolidBoxWithDashedLine
  8.     End Enum
  9.  
  10.     ' ----- The current drawing state.
  11.     Public Enum RubberBandState
  12.         Inactive
  13.         FirstTime
  14.         Active
  15.     End Enum
  16.  
  17.     ' ----- Class-level variables.
  18.     Private BasePoint As Point
  19.     Private ExtentPoint As Point
  20.     Private CurrentState As RubberBandState
  21.     Private BaseControl As Control
  22.     Public Style As RubberBandStyle
  23.     Public BackColor As Color
  24.     Public Sub New(ByVal useControl As Control, _
  25.           Optional ByVal useStyle As RubberBandStyle = _
  26.           RubberBandStyle.DashedLine)
  27.         ' ----- Constructor with one or two parameters.
  28.         BaseControl = useControl
  29.         Style = useStyle
  30.         BackColor = Color.Black
  31.     End Sub
  32.  
  33.     Public Sub New(ByVal useControl As Control, ByVal useStyle As RubberBandStyle, ByVal useColor As Color)
  34.         ' ----- Constructor with three parameters.
  35.         BaseControl = useControl
  36.         Style = useStyle
  37.         BackColor = useColor
  38.     End Sub
  39.  
  40.     Public ReadOnly Property Rectangle() As Rectangle
  41.         Get
  42.             ' ----- Return the bounds of the  rubber-band area.
  43.             Dim result As Rectangle
  44.  
  45.             ' ----- Ensure the coordinates go left to
  46.             ' right, top to bottom.
  47.             result.X = IIf(BasePoint.X < ExtentPoint.X, _
  48.                BasePoint.X, ExtentPoint.X)
  49.             result.Y = IIf(BasePoint.Y < ExtentPoint.Y, _
  50.                BasePoint.Y, ExtentPoint.Y)
  51.             result.Width = Math.Abs(ExtentPoint.X - BasePoint.X)
  52.             result.Height = Math.Abs(ExtentPoint.Y - BasePoint.Y)
  53.             Return result
  54.         End Get
  55.     End Property
  56.  
  57.     Public Sub Start(ByVal x As Integer, ByVal y As Integer)
  58.         ' ----- Start drawing the rubber band. The user must
  59.         '       call Stretch() to actually draw the first
  60.         '       band image.
  61.         BasePoint.X = x
  62.         BasePoint.Y = y
  63.         ExtentPoint.X = x
  64.         ExtentPoint.Y = y
  65.         Normalize(BasePoint)
  66.         CurrentState = RubberBandState.FirstTime
  67.     End Sub
  68.  
  69.     Public Sub Stretch(ByVal x As Integer, ByVal y As Integer)
  70.         ' ----- Change the size of the rubber band.
  71.         Dim newPoint As Point
  72.  
  73.         ' ----- Prepare the new stretch point.
  74.         newPoint.X = x
  75.         newPoint.Y = y
  76.         Normalize(newPoint)
  77.  
  78.         Select Case CurrentState
  79.             Case RubberBandState.Inactive
  80.                 ' ----- Rubber band not in use.
  81.                 Return
  82.             Case RubberBandState.FirstTime
  83.                 ' ----- Draw the initial rubber band.
  84.                 ExtentPoint = newPoint
  85.                 DrawTheRectangle()
  86.                 CurrentState = RubberBandState.Active
  87.             Case RubberBandState.Active
  88.                 ' ----- Undraw the previous band, then
  89.                 '       draw the new one.
  90.                 DrawTheRectangle()
  91.                 ExtentPoint = newPoint
  92.                 DrawTheRectangle()
  93.         End Select
  94.     End Sub
  95.  
  96.     Public Sub Finish()
  97.         ' ----- Stop drawing the rubber band.
  98.         DrawTheRectangle()
  99.         CurrentState = 0
  100.     End Sub
  101.  
  102.     Private Sub Normalize(ByRef whichPoint As Point)
  103.         ' ----- Don't let the rubber band go outside the view.
  104.         If (whichPoint.X < 0) Then whichPoint.X = 0
  105.         If (whichPoint.X >= BaseControl.ClientSize.Width) Then whichPoint.X = BaseControl.ClientSize.Width - 1
  106.  
  107.         If (whichPoint.Y < 0) Then whichPoint.Y = 0
  108.         If (whichPoint.Y >= BaseControl.ClientSize.Height) Then whichPoint.Y = BaseControl.ClientSize.Height - 1
  109.     End Sub
  110.  
  111.     Private Sub DrawTheRectangle()
  112.         ' ----- Draw the rectangle on the control or
  113.         '       form surface.
  114.         Dim drawArea As Rectangle
  115.         Dim screenStart, screenEnd As Point
  116.  
  117.         ' ----- Get the square that is the  rubber-band area.
  118.         screenStart = BaseControl.PointToScreen(BasePoint)
  119.         screenEnd = BaseControl.PointToScreen(ExtentPoint)
  120.         drawArea.X = screenStart.X
  121.         drawArea.Y = screenStart.Y
  122.         drawArea.Width = (screenEnd.X - screenStart.X)
  123.         drawArea.Height = (screenEnd.Y - screenStart.Y)
  124.  
  125.         ' ----- Draw using the user-selected style.
  126.         Select Case Style
  127.             Case RubberBandStyle.DashedLine
  128.                 ControlPaint.DrawReversibleFrame( _
  129.                    drawArea, BackColor, FrameStyle.Dashed)
  130.             Case RubberBandStyle.ThickLine
  131.                 ControlPaint.DrawReversibleFrame( _
  132.                    drawArea, BackColor, FrameStyle.Thick)
  133.             Case RubberBandStyle.SolidBox
  134.                 ControlPaint.FillReversibleRectangle( _
  135.                    drawArea, BackColor)
  136.             Case RubberBandStyle.SolidBoxWithDashedLine
  137.                 ControlPaint.FillReversibleRectangle( _
  138.                    drawArea, BackColor)
  139.                 ControlPaint.DrawReversibleFrame( _
  140.                    drawArea, Color.Black, FrameStyle.Dashed)
  141.         End Select
  142.     End Sub
  143. End Class

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 3.778 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут