日期:2014-05-18  浏览次数:20824 次

请教画矩形问题。
我第一次接触GUI,想在一张载入到pictureBox控件的图片上画一个矩形框,然后取出框的x、y、width、hight四个参数,请问如何实现画框和取参数?

------解决方案--------------------
在图片上怎么画框啊 话什么样的框 没有说清楚啊

还是给你来段代码吧
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;


public int i = 0;
public int j = 0;
public int a = 0;
public int b = 0;
public int m = 0;
public int n = 0;
public int x = 0;
public int y = 0;
private void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
//获取图片的中心点
i = this.pictureBox1.Size.Width / 2;
j = this.pictureBox1.Size.Height / 2;

//获取图片的宽高
y = this.pictureBox1.Image.Size.Width ;
x = this.pictureBox1.Image.Size.Height;

Graphics dc = this.pictureBox1.CreateGraphics();
Pen RedPen = new Pen(Color.Red, 1);
a = e.X;
b = e.Y;
if (Math.Abs(a - i) > Math.Abs(b - j))
{
//长方形的二分之一宽为
m = Math.Abs(a - i);
//长方形的二分之一高为
n = 4 * m / 5;
}
else
{
//长方形的二分之一宽为
m = Math.Abs(b - j);
//长方形的二分之一高为
n = 4 * m / 5;

//矩形的宽高比为5:4
}

if (m < this.pictureBox1.Image.Size.Width/2 && n < this.pictureBox1.Image.Size.Height/2)
{
dc.DrawRectangle(RedPen, (i - m), (j - n), 2 * m, 2 * n);
//矩形的左上角顶点坐标为(i-m,j-n) 宽 2*m 高 2*n
}
}
这些代码的功能就是在图片上双击的时候,以图片中心为基本点,画一个款高比为5:4的矩形
------解决方案--------------------
下面这段程序是在picturebox上实时绘制鼠标选中的矩形框,并弹出有关该矩形框的位置与大小信息,不知对lz有用不?

Public Class Form2

Dim PtStart, pt As Point
Dim RectSize As Size

Private Sub Pic1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Pic1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then PtStart = New Point(e.X, e.Y)
End Sub

Private Sub Pic1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Pic1.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim p As Point = PointToScreen(PtStart) : p.Offset(Pic1.Location)
If pt <> Nothing Then ControlPaint.DrawReversibleFrame(New Rectangle(p.X, p.Y, pt.X - p.X, pt.Y - p.Y), Color.Red, FrameStyle.Dashed)
pt = PointToScreen(New Point(e.X, e.Y)) : pt.Offset(Pic1.Location)
ControlPaint.DrawReversibleFrame(New Rectangle(p.X, p.Y, pt.X - p.X, pt.Y - p.Y), Color.Red, FrameStyle.Dashed)
End If
End Sub

Private Sub DrawRect(ByVal mPoint1 As Point, ByVal mPoint2 As Point)
Pic1.Refresh()
If mPoint2.X > mPoint1.X And mPoint2.Y > mPoint1.Y Then
PtStart = New Point(mPoint1.X, mPoint1.Y) : RectSize = New Size(mPoint2.X - mPoint1.X, mPoint2.Y - mPoint1.Y)
ElseIf mPoint2.X > mPoint1.X And mPoint2.Y < mPoint1.Y Then
PtStart = New Point(mPoint1.X, mPoint2.Y) : RectSize = New Size(mPoint2.X - mPoint1.X, mPoint1.Y - mPoint2.Y)
ElseIf mPoint2.X < mPoint1.X And mPoint2.Y > mPoint1.Y Then
PtStart = New Point(mPoint2.X, mPoint1.Y) : RectSize = New