110,533
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace 鼠标旋转矩形
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MouseDown += new MouseEventHandler(OnMouseDown);
MouseMove += new MouseEventHandler(OnMouseMove);
Text = "右键定点 左键拖拽";
}
int ox = -1;
int oy = -1;
int mx = 0;
int my = 0;
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
using (var path = new GraphicsPath())
{
path.AddRectangle(new Rectangle(30, 30, 230, 160));
if (ox < 0 || oy < 0)
{
g.DrawPath(Pens.Black, path);
return;
}
g.DrawLine(Pens.Red, ox - 5, oy, ox + 5, oy);
g.DrawLine(Pens.Red, ox, oy - 5, ox, oy + 5);
if (mx > 0 || my > 0)
{
var a = Math.Atan2(my - oy, mx - ox);
var n1 = (float)Math.Cos(a);
var n2 = (float)Math.Sin(a);
var n3 = -(float)Math.Sin(a);
var n4 = (float)Math.Cos(a);
var n5 = (float)((ox * (1 - Math.Cos(a)) + oy * Math.Sin(a)));
var n6 = (float)((oy * (1 - Math.Cos(a)) - ox * Math.Sin(a)));
path.Transform(new Matrix(n1, n2, n3, n4, n5, n6));
}
g.DrawPath(Pens.Black, path);
}
}
void OnMouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ox = e.X;
oy = e.Y;
mx = e.X;
my = e.Y;
Invalidate();
}
}
void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mx = e.X;
my = e.Y;
Invalidate();
}
}
}
}