gpt4 book ai didi

c# - 根据 BackColor 反转文本颜色

转载 作者:太空狗 更新时间:2023-10-29 18:21:37 25 4
gpt4 key购买 nike

我有一个像下面两个这样的 ProgressBar 控件:

enter image description here

第一个画得很好。如您所见,第二个只有一个0,它应该有两个但另一个看不到,因为ProgressBar 的ForeColorTextColor 相同。当下面的 ProgressBar 用 Lime 绘制时,有没有一种方法可以将文本绘制成黑色,而当背景为黑色时,我可以用 Lime 绘制文本?

最佳答案

您可以先绘制背景和文本,然后使用 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 属性上添加一些验证。

关于c# - 根据 BackColor 反转文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com