2012年7月4日 星期三

在 WinForm 移動及縮放圖片(Image Viewer)


此篇目的很清楚~就是希望在 WinForm 中顯示圖片,並能放大及顯示圖片
首先先在 Form 中拉進 TrackBar(縮放圖片) 及 PictureBox(圖片容器)
透過 TackBar 的 Scroll 事件來變更圖片縮放比例
透過 PictureBox 的 MouseDown 事件來啟動移動狀態,並記錄位移的初始點
再透過 MouseMove 事件來計算位移量,並改變 PictureBox 的座標
透過 MouseUp 事件來結束移動狀態

範例如下:
##CONTINUE##

















Imports System.Drawing
Imports System.Windows.Forms

Public Class frmImageViewer
    Private _ImagePath As String
    Private _ImageWidth As Integer
    Private _ImageHeight As Integer

    Private _StarPoint As Point = Point.Empty
    Private _ViewPoint As Point = Point.Empty
    Private bMoveImage As Boolean = False

    Public Sub New(sImagePath As String)
        InitializeComponent()
        _ImagePath = sImagePath
        _ImageWidth = picImage.Width
        _ImageHeight = picImage.Height
    End Sub

    Private Sub frmImageViewer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        picImage.ImageLocation = _ImagePath
    End Sub



    Private Sub TrackBar1_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBar1.Scroll
        picImage.Width = _ImageWidth * (TrackBar1.Value / 100)
        picImage.Height = _ImageHeight * (TrackBar1.Value / 100)
    End Sub

    Private Sub picImage_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles picImage.MouseDown
        bMoveImage = True
        Cursor = Cursors.Hand
        _StarPoint = e.Location
    End Sub

    Private Sub picImage_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles picImage.MouseMove
        If bMoveImage Then
            Dim _MovePoint As New Point(e.X - _StarPoint.X, e.Y - _StarPoint.Y)
            _ViewPoint.X = _MovePoint.X + _ViewPoint.X
            _ViewPoint.Y = _MovePoint.Y + _ViewPoint.Y
            picImage.Location = New Point(_ViewPoint.X, _ViewPoint.Y)
        End If
    End Sub

    Private Sub picImage_MouseUp(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles picImage.MouseUp
        bMoveImage = False
    End Sub
End Class



沒有留言:

張貼留言