根据BackColor反转文本颜色

问题描述 投票:8回答:1

我有一个像以下两个ProgressBar控件:

enter image description here

第一个画得很好。正如你所看到的,第二只有一个0,它应该有两个,但另一个不能被看到,因为ProgressBar的ForeColorTextColor相同。当下面的ProgressBar用Lime绘制时,我可以用黑色绘制文本,并在背景为黑色时在Lime中绘制文本吗?

c# .net winforms gdi+ gdi
1个回答
12
投票

您可以先绘制背景和文本,然后使用PatBlt方法使用PATINVERT参数绘制前景石灰矩形,以将前景绘图与背景图形组合:

enter image description here

enter image description here

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyProgressBar : Control
{
    public MyProgressBar() 
    {
        DoubleBuffered = true;
        Minimum = 0; Maximum = 100; Value = 50;
    }
    public int Minimum { get; set; }
    public int Maximum { get; set; }
    public int Value { get; set; }
    protected override void OnPaint(PaintEventArgs e) 
    {
        base.OnPaint(e);
        Draw(e.Graphics);
    }
    private void Draw(Graphics g) 
    {
        var r = this.ClientRectangle;
        using (var b = new SolidBrush(this.BackColor))
            g.FillRectangle(b, r);
        TextRenderer.DrawText(g, this.Value.ToString(), this.Font, r, this.ForeColor);
        var hdc = g.GetHdc();
        var c = this.ForeColor;
        var hbrush = CreateSolidBrush(((c.R | (c.G << 8)) | (c.B << 16)));
        var phbrush = SelectObject(hdc, hbrush);
        PatBlt(hdc, r.Left, r.Y, (Value * r.Width / Maximum), r.Height, PATINVERT);
        SelectObject(hdc, phbrush);
        DeleteObject(hbrush);
        g.ReleaseHdc(hdc);
    }
    public const int PATINVERT = 0x005A0049;
    [DllImport("gdi32.dll")]
    public static extern bool PatBlt(IntPtr hdc, int nXLeft, int nYLeft,
        int nWidth, int nHeight, int dwRop);
    [DllImport("gdi32.dll")]
    public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
    [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
    public static extern bool DeleteObject(IntPtr hObject);
    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateSolidBrush(int crColor);
}

注意:控件仅用于演示绘制逻辑。对于真实世界的应用程序,您需要在MinimumMaximumValue属性上添加一些验证。

© www.soinside.com 2019 - 2024. All rights reserved.