C# WinForm 解决TextureBrush,FillRectangle绘图偏移问题

来源:互联网 发布:软件可靠性加速测试 编辑:程序博客网 时间:2024/05/16 02:35

FillRectangle方法

最近在开发WinForm软件中遇到使用FillRectangle方法窗体绘制园角图象的时候总是发生偏移错位问题,使我头疼了半天,其现象如下:

C# <wbr>WinForm <wbr>解决TextureBrush,FillRectangle绘图偏移问题

代码如下:

private void DrawSideTop_Right(Graphics e)
                
            TextureBrush brush = new TextureBrush(TopSide_RightImage, new Rectangle(0, 0, 5, 30));
            e.FillRectangle(brush,Width - 5, 0, 5, 30);
         
       
        }

观察其左上角却没有一点偏差,那么为什么右会出现偏差现象呢?问题究竟是出在什么地方?我在程序中试着改变其填充位置,无论是向左改变数字(Width - 4)还是向左改变都会有一个象素的偏移误差.无奈之下我找遍了Baidu和Google没有一点收获.

问题是出在FillRectangle方法上还是出在TextureBrush中呢?后来终于在一个网友的博客中找到了答案:问题就出在TextureBrush中,在这里就不讲TextureBrush究竟为什么为出现这样的问题了,我只认为我的感觉是正确的FillRectangle绘出图形后确实是向左偏移了1象素(也有网友说是向上,向左各偏移了0.5象素),

如何才能使它正确显示呢?解决办法是:用TextureBrush的TranslateTransform方法,

TranslateTransform是把原始图像的起始位置进行偏移,在使用FillRectangle绘制出图象之前先,我们将它先向左偏移一个象素,于是我把程序改成如下:

private void DrawSideTop_Right(Graphics e)
                
            TextureBrush brush = new TextureBrush(TopSide_RightImage, new Rectangle(0, 0, 5, 30));
           
brush.TranslateTransform(Width - 5, 0);
            e.FillRectangle(brush, Width - 5, 0, 5, 30);
         
       
        }

经过以上的改动终于可以正确显示了