Files
lserp_cs_6.0/插件库/Lskj.Main/Control/BackgroundPanel.cs
T
2026-07-02 10:11:39 +00:00

74 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Lskj.Main.Control
{
public partial class BackgroundPanel :Panel
{
private Image _originalBackgroundImage;
// 公开属性:设置/获取背景图片
public Image BackgroundImageCustom
{
get => _originalBackgroundImage;
set
{
_originalBackgroundImage = value;
Invalidate(); // 设置图片后立即重绘
}
}
public BackgroundPanel()
{
// 关键设置:关闭Panel默认背景,启用双缓冲减少闪烁
this.BackgroundImage = null;
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
}
// 重写OnPaint方法,手动绘制背景图
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 图片为空时直接返回
if (_originalBackgroundImage == null) return;
// 1. 计算等比缩放比例(以Panel的ClientSize为基准)
float scaleX = (float)this.ClientSize.Width / _originalBackgroundImage.Width;
float scaleY = (float)this.ClientSize.Height / _originalBackgroundImage.Height;
float scale = Math.Min(scaleX, scaleY); // 取较小值,避免图片超出Panel
// 2. 计算图片绘制的位置(居中显示)
int newWidth = (int)(_originalBackgroundImage.Width * scale);
int newHeight = (int)(_originalBackgroundImage.Height * scale);
int x = (this.ClientSize.Width - newWidth) / 2;
int y = (this.ClientSize.Height - newHeight) / 2;
// 3. 高质量绘制图片(抗锯齿、高清缩放)
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
e.Graphics.DrawImage(_originalBackgroundImage, new Rectangle(x, y, newWidth, newHeight));
}
// Panel大小变化时触发重绘
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate(); // 标记控件需要重绘
}
}
}