绘制文本反转现有颜色

时间:2017-01-14 08:19:55

标签: c# gdi+ objectlistview

我认为在进度条上显示倒置百分比是相当常见的。见下面的例子。 enter image description here enter image description here

我正在使用Phillip Piper的名为ObjectListView的库,它有BarRenderer。这是好的,除了它没有百分比在酒吧。所以,我决定在它上面绘制百分比。

    class ProgressRender:BarRenderer
    {
        public override bool RenderSubItem(DrawListViewSubItemEventArgs e,
            Graphics g, Rectangle cellBounds, object model)
        {
            base.RenderSubItem(e, g, cellBounds, model);
            Font f = new Font("Tahoma", 8f);
            StringFormat format = new StringFormat();
            format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Center;
            g.DrawString("50%", f, new SolidBrush(Color.Black), cellBounds, format);
            return true;
        }
    }

问题是,正如您所看到的,文本颜色固定为Color.Black。有没有办法让文字的颜色反转下面的颜色?

enter image description here

如果我不能简单地在现有栏上画“倒置文字”,我可以继承BaseRenderer而不是BarRender,并自己绘制栏。我使用the "cheating" described in this question实现了以下代码,但我不确定这是否是最好的方法。我附上了它,以防有相同问题的人在将来阅读这个问题。

class ProgressRender:BaseRenderer
{
    public override bool RenderSubItem(DrawListViewSubItemEventArgs e,
        Graphics g, Rectangle cellBounds, object model)
    {
        Font f = new Font("Tahoma", 8f);
        StringFormat format =
            new StringFormat
            {
                FormatFlags = StringFormatFlags.NoWrap,
                Trimming = StringTrimming.None
            };
        float value = 20.0f;
        var valueString = $"{value:0.0}%";
        var backgroundBrush = new SolidBrush(Color.White);
        var barBrush = new SolidBrush(Color.MidnightBlue);

        //painting the black part of the text first
        var stringSize = g.MeasureString(valueString, f);
        var stringX = cellBounds.X + (cellBounds.Width - stringSize.Width) / 2;
        var stringY = cellBounds.Y + (cellBounds.Height - stringSize.Height) / 2;
        g.DrawString(valueString, f, barBrush, stringX, stringY);

        //painting the progress rectangle(it would cover the part to be hidden)
        var barWidth = cellBounds.Width * value / 100; 
        var barRect = new RectangleF(cellBounds.X, cellBounds.Y, barWidth, cellBounds.Height);
        g.FillRectangle(barBrush, barRect);

        //painting the white text over the progress rectangle only(clipping it)
        if (barRect.Right >= stringX)
        {
            var clippedRect = new RectangleF(stringX, stringY, barRect.Right-stringX, stringSize.Height);
            g.DrawString(valueString, f, backgroundBrush, clippedRect, format);
        }

        return true;
    }
}

0 个答案:

没有答案