c# 窗体控件上绘制跟随鼠标的十字线
一.技术路线
(1)以自定义大小的image为画布,绘制窗体控件显示的主题内容
public Image img=new Bitmap(250,250); //定义img
Graphics gr = Graphics.FromImage(img); //img用作画布,绘制控件中显示的主题内容;
____________________________
在img画布上绘制显示内容
gr.DrawLine(pen,point1,point2);
gr.Draw.........
...............
____________________________
(2)将(1)中完成的image加载到控件上,类似背景图片
Graphics grv =pb.CreateGraphics();
grv.DrawImage(img,ClientRectangle); // ClientRectangle参数设置img适应控件大小
(3)利用MouseMove事件动态绘制十字光标
private void pb1_MouseMove(object sender, MouseEventArgs e)
{
Point pt1_1 = new Point(e.X,0);
Point pt1_2 = new Point(e.X,ClientRectangle.Height);
Point pt2_1 = new Point(0,e.Y);
Point pt2_2 = new Point(ClientRectangle.Width, e.Y);
Graphics grvisual = pb1.CreateGraphics();
grvisual.DrawImage(img, ClientRectangle);
Pen pen = new Pen(Color.Brown,5);
pen.DashStyle = DashStyle.DashDotDot;
grvisual.DrawLine(pen, pt1_1, pt1_2);
grvisual.DrawLine(pen, pt2_1, pt2_2);
}
二.实现代码
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 testMouseEvent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Image img = new Bitmap(250,350);
private void pb1_MouseMove(object sender, MouseEventArgs e)
{
tb1.Text = e.X.ToString();
tb2.Text = e.Y.ToString();
Point pt1_1 = new Point(e.X,0);
Point pt1_2 = new Point(e.X,ClientRectangle.Height);
Point pt2_1 = new Point(0,e.Y);
Point pt2_2 = new Point(ClientRectangle.Width, e.Y);
Graphics grvisual = pb1.CreateGraphics();
grvisual.DrawImage(img, ClientRectangle);
Pen pen = new Pen(Color.Brown,5);
pen.DashStyle = DashStyle.DashDotDot;
grvisual.DrawLine(pen, pt1_1, pt1_2);
grvisual.DrawLine(pen, pt2_1, pt2_2);
}
private void button1_Click(object sender, EventArgs e)
{
Graphics gr = Graphics.FromImage(img);
Random rd = new Random();
gr.FillRectangle(Brushes.White, ClientRectangle);
for (int x = 0; x < ClientRectangle.Width; x++)
{
for (int y = 0; y < ClientRectangle.Height; y++)
{
Color c = Color.FromArgb(rd.Next(255), rd.Next(255), rd.Next(255));
using (Pen p = new Pen(c, 1))
{
gr.DrawLine(p, new Point(0, 0), new Point(x, y));
}//of using
}//of for_1_2
Graphics grv = pb1.CreateGraphics();
grv.DrawImage(img, ClientRectangle);
}//of for_1
}
}
}
三.实现效果
*本文疏漏错误在所难免,望大家提出宝贵的意见和建议!