C# - DrawBorder - 底部和右侧不可见

时间:2018-03-17 20:43:58

标签: c#

我想为元素的每一面添加不同的bordercolor, 但它工作得很好,我得到的唯一问题是边框的右侧和底侧是不可见的。

        public static void DrawBorder
    (
        Graphics graphics, Rectangle bounds,
        Color leftColor, int leftWidth, ButtonBorderStyle leftStyle,
        Color topColor, int topWidth, ButtonBorderStyle topStyle,
        Color rightColor, int rightWidth, ButtonBorderStyle rightStyle,
        Color bottomColor, int bottomWidth, ButtonBorderStyle bottomStyle
    ){}
    Color leftColor = Color.FromArgb(65,0,0,0), rightColor = Color.FromArgb(150, 0, 0, 0), topColor = Color.FromArgb(65, 0, 0, 0), bottomColor = Color.FromArgb(150, 0, 0, 0);
    int leftWidth = 3, rightWidth = 3, topWidth = 3, bottomWidth = 3;
    ButtonBorderStyle leftStyle = ButtonBorderStyle.Solid, rightStyle = ButtonBorderStyle.Solid, topStyle = ButtonBorderStyle.Solid, bottomStyle = ButtonBorderStyle.Solid;

    private void Paint_(object sender, PaintEventArgs e)
    {
        Rectangle borderRectangle = this.ClientRectangle;
        borderRectangle.Inflate(0, 0);
        ControlPaint.DrawBorder(e.Graphics, borderRectangle,
        leftColor, leftWidth, leftStyle,
        topColor, topWidth, topStyle,
        rightColor, rightWidth, rightStyle,
        bottomColor, bottomWidth, bottomStyle);
    }

我正在使用" Paint _"你在这里看到的每一个元素的功能,所以每个元素都有同样的问题。 Missing right and bottom border 我对#34; Draw"中的任何一个都很陌生。东西,所以我不知道任何可能是问题的东西。

1 个答案:

答案 0 :(得分:0)

接受Draw...实例的Pen调用似乎(默认情况下)在右侧和底部绘制一个大于1像素的矩形。因此,如果您调用类似DrawRectangle(Pens.Black, 0, 0, 100, 100)的内容,屏幕上的矩形看起来就像是跨越坐标0,0到101,101。

此处描述了这背后的原因:Pixel behaviour of FillRectangle and DrawRectangle

要快速修复绘图,只需将小于1像素的坐标向右或向下传递。例如,为了修复上面的例子,你可以调用DrawRectangle(0, 0, 99, 99)来接收一个跨越屏幕上坐标0,0到100,100的矩形。

我个人已经停止使用PensDraw调用带边矩形,并且总是使用两个FillRectangle调用(使用Brush个实例),如下所示:

// Draws a white rectangle with black border
Rectangle rect = new Rectangle(0, 0, 100, 100);
gr.FillRectangle(Brushes.Black, rect); // Draw border
rect.Inflate(-1, -1); // Decrease the size of the rectangle by 1 pixel on all sides
gr.FillRectangle(Brushes.White, rect); // Draw background above it

我已经读过FillRectangleDrawRectangle更快(因为它可以简单地对该区域进行bitblit,而不像Draw那样需要在内部绘制具有所有可能的恶作剧的单独行。)< / p>