C#滚动条的使用

时间:2023-01-27 09:01:08

HScroll的min为0,max为20,value为10,则当前水平滚动条显示在中间部位。
当hScroll与绘制的图结合,想要让hScroll滑动一整行,图正好移动到最后,可以这样写:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
//Region c = g.Clip;
//g.Clip = new Region(new Rectangle(100, 50, 200, 100));
//Scale1(6F);
g.DrawLine(new Pen(new SolidBrush(Color.Red), 1), 100, 500, 1040, 500);
g.DrawLine(new Pen(new SolidBrush(Color.Red), 1), 100, 500, 100, 50);
g.DrawLine(new Pen(new SolidBrush(Color.Red), 1), 100, 50, 1040, 50);
g.DrawLine(new Pen(new SolidBrush(Color.Red), 1), 1040, 500, 1040, 50);
PointF[] m_pointList = new PointF[51];
for (int i = 0; i <= 50; i++)
{
PointF f = new PointF(100 + 14 * i - hScrollBar1.Value, 50 + 9 * i);
m_pointList[i] = f;
}
g.DrawLines(new Pen(new SolidBrush(Color.Blue)), m_pointList);
}
此处,x最大值为700,我们将滚动条的maximum设为700+largeChange,这样,当滚动条滑动到最右侧,图也绘制到了最右侧。
而如果,我们想要放大缩小和滚动相结合,比如,放大到2倍,则每个点的x都扩大为2倍,
for (int i = 0; i <= 50; i++)
{
PointF f = new PointF(100 + 14 2 i - hScrollBar1.Value, 50 + 9 * i);
m_pointList[i] = f;
}
同时,Hscroll的maximum应该设为2*700 + largeChange。

public void UpdateScrollBar()
{
if (viewControl1.Width <= 0 || viewControl1.Height <= 0)
{
return;
}
hScrollBar1.Visible = viewControl1.MyScale > 1.0;

        // 水平滚动条
int maxMS = 940;//GetMaximumWidth();
float TimeScale = viewControl1.MyScale;
float totalWidth = maxMS * (TimeScale - 1);
// 计算滑块在原有配置下和最大值的相对位置
//float oldValueRate = 0.0F;
//if (hScrollBar1.Maximum != 0)
//{
// oldValueRate = hScrollBar1.Value * 1.0F / hScrollBar1.Maximum;
//}
hScrollBar1.Maximum = (int)(totalWidth) + hScrollBar1.LargeChange; //timeAxis.Width / 2;
//hScrollBar1.LargeChange = (int)TimeScale;
// 新配置下保持和新的最大值相对位置(不能超过最大可移动范围)
//hScrollBar1.Value = (int)(hScrollBar1.Maximum * oldValueRate);
hScrollBar1.Value = 0;
}

TimeSpan totalTs = m_dateTimeList[m_count - 1].Subtract(m_dateTimeList[0]).Duration();
double totalSeconds = totalTs.TotalSeconds;

        PointF[] pointList = new PointF[m_count];
for (int i = 0; i < m_count; i++)
{
TimeSpan ts = m_dateTimeList[i].Subtract(m_dateTimeList[0]).Duration();
double sec = ts.TotalSeconds;
float x = (float)(sec * 940 * m_scale / totalSeconds);
float y = 500.0f;
int index = i;
if (m_maxValue != m_minValue && index < m_count)
{
long value = m_dataList[index];
if (m_units == Units.MB)
{
value /= (1024 * 1024);
}
else if (m_units == Units.KB)
{
value /= 1024;
}
y = 500 - (value - m_minValue) * 450 / (m_maxValue - m_minValue);
}
if (y > 500)
{
y = 500;
}
if (y < 50)
{
y = 50;
}
//x = x * m_scale + 100 - m_startX;
x = x + 100 - m_startX;
pointList[i] = new PointF(x, y);
}
if (pointList.Length > 1)
{
Region c = g.Clip;
g.Clip = new Region(new Rectangle(100, 50, 940, 450));
g.DrawLines(new Pen(new SolidBrush(Color.Blue)), pointList);
g.Clip = c;
}