111,125
社区成员
发帖
与我相关
我的任务
分享const int TEXT_COUNT = 100; // 文字的个数
const int TEXT_HEIGHT = 10; // 单个文字的高
const int TEXT_WIDTH = 20; // 单个文字的宽
Rectangle[] textRectangle = new Rectangle[TEXT_COUNT]; // 文字出现的区域
string[] labelText = new string[TEXT_COUNT]; // 文字的内容
int moveIndex = -1; // 鼠标停留在第几个文字
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
labelText[i] = i.ToString("00");
textRectangle[i] = new Rectangle(
(i % 10) * TEXT_WIDTH, (i / 10) * TEXT_HEIGHT,
TEXT_WIDTH, TEXT_HEIGHT);
}
}
private void DrawTexts(Graphics AGraphics) // 绘制全部的文字
{
for (int i = 0; i < 100; i++)
{
AGraphics.DrawString(labelText[i], Font, new SolidBrush(ForeColor),
textRectangle[i]);
}
if (moveIndex >= 0)
AGraphics.DrawString(labelText[moveIndex], Font, new SolidBrush(Color.Red),
textRectangle[moveIndex]);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
DrawTexts(e.Graphics);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
int vMoveIndex = -1;
for (int i = 0; i < 100; i++)
{
if (textRectangle[i].Contains(e.Location))
{
vMoveIndex = i; // 得到鼠标停留的文字序号
break;
}
}
if (vMoveIndex != moveIndex)
{
moveIndex = vMoveIndex;
Graphics vGraphics = ((Panel)sender).CreateGraphics();
DrawTexts(vGraphics); // 这里可以进一步优化,考虑只绘制发状态改变的文字
vGraphics.Dispose();
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (moveIndex >= 0)
{
MessageBox.Show(moveIndex.ToString("00"));
Point mousePosition = ((Panel)sender).PointToScreen(Control.MousePosition);
int vMoveIndex = -1;
for (int i = 0; i < 100; i++)
{
if (textRectangle[i].Contains(mousePosition))
{
vMoveIndex = i;
break;
}
}
if (vMoveIndex != moveIndex)
{
moveIndex = vMoveIndex;
Graphics vGraphics = ((Panel)sender).CreateGraphics();
DrawTexts(vGraphics);
vGraphics.Dispose();
}
}
}