如何找到图像的中心点?

时间:2014-02-04 13:28:38

标签: vb.net image-processing crop

我想将Crop Control放在图片框图像的中心。我试过以下代码

Dim oCropControl As new CropControl
Dim oControlLocation As Point

oControlLocation = New Point(peImageViewer.Width / 2, peImageViewer.Height / 2)
oCropControl.Location = New Point(oControlLocation.X, oControlLocation.Y)

但是效果不好.. :(作物控制显示在底部。

提前致谢!!

1 个答案:

答案 0 :(得分:2)

假设他们都是同一控件的父级,你可以这样做:

Dim rect1 As Rectangle = Me.myPictureBox.Bounds
Dim rect2 As Rectangle = Me.myCropControl.Bounds

rect2.X = CInt(rect1.X + ((rect1.Width / 2) - (rect2.Width / 2)))
rect2.Y = CInt(rect1.Y + ((rect1.Height / 2) - (rect2.Height / 2)))

Me.myCropControl.Bounds = rect2
Me.myCropControl.BringToFront()

示例

Public Class Form1

    Public Sub New()
        Me.InitializeComponent()
        Me.Size = New Size(400, 400)
        Me.StartPosition = FormStartPosition.CenterScreen
        Me.myButton = New Button() With {.Location = New Point(3, 3), .Text = "ALIGN!"}
        Me.myCropControl = New Label() With {.Bounds = New Rectangle(245, 263, 60, 60), .BackColor = Color.Blue, .ForeColor = Color.White, .Text = "CROP", .TextAlign = ContentAlignment.MiddleCenter}
        Me.myPictureBox = New PictureBox() With {.Bounds = New Rectangle(23, 56, 246, 143), .BackColor = Color.Red}
        Me.Controls.AddRange({Me.myButton, Me.myCropControl, Me.myPictureBox})
    End Sub

    Private Sub Align(sender As Object, e As EventArgs) Handles myButton.Click
        Dim rect1 As Rectangle = Me.myPictureBox.Bounds
        Dim rect2 As Rectangle = Me.myCropControl.Bounds
        rect2.X = CInt(rect1.X + ((rect1.Width / 2) - (rect2.Width / 2)))
        rect2.Y = CInt(rect1.Y + ((rect1.Height / 2) - (rect2.Height / 2)))
        Me.myCropControl.Bounds = rect2
        Me.myCropControl.BringToFront()
    End Sub

    Private WithEvents myButton As Button
    Private myCropControl As Label
    Private myPictureBox As PictureBox

End Class