summary
To develop a simple thermometer control under C# WinForm, you mainly need to use the technology of the Windows graphical user interface (GUI) and combine the . The related technologies of the .NET framework and the underlying functionality of the Windows operating system enable an intuitive, easy-to-use interface and data processing functions.
body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gdi104
{
public class TemperatureGauge : Control
{
private int minValue = 0;
private int maxValue = 100;
private int currentValue = 50;
public int MinValue
{
get { return minValue; }
set { minValue = value; Invalidate(); }
}
public int MaxValue
{
get { return maxValue; }
set { maxValue = value; Invalidate(); }
}
public int CurrentValue
{
get { return currentValue; }
set
{
if (value < minValue)
currentValue = minValue;
else if (value > maxValue)
currentValue = maxValue;
else
currentValue = value;
Invalidate();
}
}
public TemperatureGauge()
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
Width = 60; // 控制宽度以控制温度计的高度
Height = 300; // 控制高度以控制温度计的宽度
BackColor = Color.WhiteSmoke;
Padding = new Padding(2, 20, 2, 20);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// 绘制背景
g.FillRectangle(Brushes.White, Padding.Left, Padding.Top, Width - Padding.Horizontal, Height - Padding.Vertical);
// 绘制边框
g.DrawRectangle(Pens.AliceBlue, Padding.Left, Padding.Top, Width - Padding.Horizontal - 1, Height - Padding.Vertical - 1);
// 绘制刻度线
for (int i = minValue; i <= maxValue; i += 10)
{
float yPos = (float)(maxValue - i) / (maxValue - minValue) * (Height - Padding.Vertical) + Padding.Top;
g.DrawLine(Pens.Black, Padding.Left + 10, yPos, Padding.Left + 20, yPos);
g.DrawString(i.ToString(), Font, Brushes.Black, Padding.Left + 25, yPos - 10);
}
// 绘制水银柱
float indicatorY = (float)(maxValue - currentValue) / (maxValue - minValue) * (Height - Padding.Vertical) + Padding.Top;
float mercuryHeight = (Height - Padding.Vertical) - (indicatorY - Padding.Top);
g.FillRectangle(Brushes.Red, Padding.Left + 10, indicatorY, 10, mercuryHeight);
}
}
}