裁剪(二)

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
//create essensial objects for painting text strings
SizeF sizeF = g.MeasureString("Test", this.Font);
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
//set properties of the grid
int cellHeight = (int)sizeF.Height + 4;
int cellWidth = 80;
int nbrColumns = 50;
int nbrRows = 50;
//output general info to console
Console.WriteLine("-------------------------");
Console.WriteLine("e.ClipRectangle = " + e.ClipRectangle);
Console.WriteLine("The following cells need to be redrawn " + "(in whole or in part):");
//draw the cells and the output to console
for (int row = 0; row < nbrRows; ++row)
{
for (int col = 0; col < nbrColumns; ++col)
{
Point cellLocation = new Point(col * cellWidth, row * cellHeight);
Rectangle cellRect = new Rectangle(cellLocation.X, cellLocation.Y, cellWidth, cellHeight);
if (cellRect.IntersectsWith(e.ClipRectangle))
{
Console.WriteLine("Row:{0} cel:{1}", row, col);
g.FillRectangle(Brushes.LightBlue, cellRect);
g.DrawRectangle(Pens.Black, cellRect);
string s = String.Format("{0},{1}", col, row);
g.DrawString(s, this.Font, Brushes.Black, cellRect, sf);
}
else
{
}
}



这段代码中的if语句指出,只有矩形与ClipRectangle的交集不为空,事件处理程序才将创建此矩形。
换句话说,如果操作系统不打算向绘图表面提交矩形的至少部分区域,它将不会创建矩形。
如果没有if。。else语句,事件处理程序将需要生成50行和50列,也就是2500个矩形,
但是if。。else语句将每一个矩形的预定位置与clipRectangle进行比较,所以代码生成的唯一矩形是实际绘制到可视的绘图表面的那些矩形。

可以通过Graphics。IsVisibleClipEmpty测试代替Rectangle。IntersectsWith测试来实现一个类似的效果,
即将if语句改为if(!g.IsVisibleClipEmpty)区别是IntersectsWith把每一个矩形与裁剪矩形比较,IsVisibleClipEmpty把每一个矩形与客户矩形比较。



 

posted @ 2012-03-14 20:12  ttssrs  阅读(179)  评论(0编辑  收藏  举报