根据BackColor反转文本颜色 [英] Invert Text Color depending on BackColor

查看:99
本文介绍了根据BackColor反转文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ProgressBar控件,类似于以下两个:

I have a ProgressBar control like the following two:

第一个已正确绘制.如您所见,第二个只有一个0,应该有两个,但是另一个看不见,因为ProgressBar的ForeColorTextColor相同.有什么方法可以将下面的ProgressBar用石灰涂成黑色,将背景涂成黑色?

The first is painted properly. As you can see, the second only has one 0, it's supposed to have two but the other cannot be seen because ProgressBar's ForeColor is the same as the TextColor. Is there a way I can paint the text in black when the ProgressBar below is painted in Lime and paint the text in Lime when the background is black?

推荐答案

您可以先绘制背景和文本,然后使用

You can first draw the background and text, then draw the foreground lime rectangle using PatBlt method with PATINVERT parameter to combine foreground drawing with background drawing:

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属性上添加一些验证.

Note: The controls is just for demonstrating the paint logic. For a real world application, you need to add some validation on Minimum, Maximum and Value properties.

这篇关于根据BackColor反转文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆