设置高度的带图片Button控件AutoEllipsis属性失效问题求助
代码示例
_BtnDump = new Button(); _BtnDump.Name = "dum" + i; _BtnDump.Text = data.DumpName; _BtnDump.Width = 98; _BtnDump.Height = 52; //add icon dump puja _BtnDump.Image = Image.FromFile(@"Images\dump.ico"); _BtnDump.TextAlign = ContentAlignment.MiddleCenter; _BtnDump.TextImageRelation = TextImageRelation.TextAboveImage; // Below code is not work yet. the layout get screwed //_BtnDump.Font = new Font("Microsoft Sans Serif", 11); //new methode _BtnDump.Visible = true; _BtnDump.AutoSize = false; _BtnDump.AutoEllipsis = true; _BtnDump.TextAlign = ContentAlignment.MiddleCenter;
问题描述
将Button高度从默认23改为52后,文本自动变成多行且AutoEllipsis不生效。需求是设置固定高度的同时,让文本保持单行并显示省略号——因为要在按钮下方显示图片,文本多行时会裁剪图片。
补充说明:使用他人提供的代码后,图片不再被裁剪,但图片区域被压缩;设置TextImageRelation.ImageAboveText时,图片始终位于底部,达不到预期布局效果。
解决方法
1. 让AutoEllipsis生效并保持文本单行
WinForms的AutoEllipsis生效需要AutoSize=false,但按钮高度过大时默认布局会自动换行,可通过以下方式限制:
- 调整
Padding,给文本区域预留刚好适配单行的高度,避免换行 - 切换到GDI+渲染,提升
AutoEllipsis稳定性
示例代码:
_BtnDump = new Button(); _BtnDump.Name = "dum" + i; _BtnDump.Text = data.DumpName; _BtnDump.Width = 98; _BtnDump.Height = 52; _BtnDump.Image = Image.FromFile(@"Images\dump.ico"); _BtnDump.TextImageRelation = TextImageRelation.TextAboveImage; _BtnDump.Visible = true; _BtnDump.AutoSize = false; _BtnDump.AutoEllipsis = true; _BtnDump.TextAlign = ContentAlignment.TopCenter; // 文本顶对齐,预留图片空间 _BtnDump.Padding = new Padding(2, 2, 2, 22); // 底部留padding给图片,压缩文本区域高度 _BtnDump.UseCompatibleTextRendering = true; // 启用GDI+渲染,确保AutoEllipsis生效
2. 修复图片布局异常
图片压缩、位置错误是因为默认布局逻辑会分配剩余空间给图片区域,可通过以下方式调整:
- 明确设置
ImageAlign配合TextImageRelation控制位置 - 手动指定图片尺寸,避免被拉伸
示例代码:
// 控制图片位置 _BtnDump.ImageAlign = ContentAlignment.BottomCenter; _BtnDump.TextImageRelation = TextImageRelation.ImageAboveText; _BtnDump.Padding = new Padding(5, 5, 5, 5); // 调整内边距,拉开文本与图片间距 // 避免图片压缩 Bitmap img = new Bitmap(@"Images\dump.ico"); img = new Bitmap(img, new Size(24, 24)); // 手动设置目标尺寸 _BtnDump.Image = img;
3. 自定义Button控件(彻底解决布局问题)
如果上述方法仍不满足需求,可重写OnPaint方法,完全控制文本和图片的绘制逻辑:
public class CustomButton : Button { protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(BackColor); // 绘制单行文本,带省略号 StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Near; sf.Trimming = StringTrimming.EllipsisCharacter; sf.FormatFlags = StringFormatFlags.NoWrap; Rectangle textRect = new Rectangle(0, 0, Width, Height - 28); // 预留图片高度 e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), textRect, sf); // 绘制底部居中的图片 if (Image != null) { int imgX = (Width - Image.Width) / 2; int imgY = Height - Image.Height - 4; // 底部留4px间距 e.Graphics.DrawImage(Image, imgX, imgY, Image.Width, Image.Height); } } }
使用自定义控件:
_BtnDump = new CustomButton(); // 其他属性按需求设置即可
内容的提问来源于stack exchange,提问作者Puja Surya
相关产品推荐
相关产品推荐

