能给我一个在VS2010新建的控件类中绘制一个全向虚拟摇杆的示例代码吗
时间: 2023-02-24 19:36:22 浏览: 57
好的,下面是一个简单的示例代码:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace VirtualJoystick
{
public partial class VirtualJoystickControl : UserControl
{
private Point centerPoint;
private Point currentPoint;
private int radius;
public VirtualJoystickControl()
{
InitializeComponent();
this.DoubleBuffered = true;
centerPoint = new Point(this.Width / 2, this.Height / 2);
radius = Math.Min(this.Width, this.Height) / 3;
currentPoint = centerPoint;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillEllipse(Brushes.DarkGray, centerPoint.X - radius, centerPoint.Y - radius, radius * 2, radius * 2);
e.Graphics.FillEllipse(Brushes.Red, currentPoint.X - radius / 2, currentPoint.Y - radius / 2, radius, radius);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (IsInCircle(e.Location))
{
currentPoint = e.Location;
this.Invalidate();
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
if (IsInCircle(e.Location))
{
currentPoint = e.Location;
}
else
{
currentPoint = GetPointOnCircle(e.Location);
}
this.Invalidate();
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
currentPoint = centerPoint;
this.Invalidate();
}
private bool IsInCircle(Point p)
{
return GetDistance(p, centerPoint) <= radius;
}
private Point GetPointOnCircle(Point p)
{
double angle = GetAngle(centerPoint, p);
int x = (int)(centerPoint.X + radius * Math.Cos(angle));
int y = (int)(centerPoint.Y + radius * Math.Sin(angle));
return new Point(x, y);
}
private double GetDistance(Point p1, Point p2)
{
int a = p1.X - p2.X;
int b = p1.Y - p2.Y;
return Math.Sqrt(a * a + b * b);
}
private double GetAngle(Point p1, Point p2)
{
int a = p2.X - p1.X;
int b = p2
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)