如何在 WinForms 按钮的文本之前添加图像图标?

问题描述

我正在尝试在 WinForms 按钮 87x30 大小的文本之前添加 .ico 48x48 图像:

  button1.BackgroundImageLayout = ImageLayout.Stretch;  
  button1.BackgroundImageLayout = ImageLayout.None;                 
  button1.BackgroundImageLayout = ImageLayout.Zoom;  
  button1.ImageAlign = ContentAlignment.MiddleLeft;
  button1.TextimageRelation = TextimageRelation.ImageBeforeText;
  button1.TextAlign = ContentAlignment.MiddleRight;

结果是:

enter image description here

我想弄清楚,如何将左侧的图像与相关距离上的文本对齐,如下所示:

enter image description here

编辑:

    button1.TextimageRelation = TextimageRelation.ImageBeforeText;
    button1.TextAlign = ContentAlignment.MiddleLeft; /// MiddleRight; // MiddleCenter; 
    button1.ImageAlign = ContentAlignment.MiddleRight; /// MiddleLeft;

结果:

enter image description here

enter image description here

解决方法

背景图片属性就像操作系统的桌面背景,是一张壁纸,可以拉伸、调整、重复...

因此,在这里您不需要将 BackgroundImage 用于与其文本相关联的按钮图标样式图像。

如果您使用 Image 属性并将对齐方式设置为左对齐和文本右对齐,则一切正常:

enter image description here

enter image description here

然后,您可以根据图像大小和/或文本大小和长度调整这些对齐方式以及宽度和高度以达到所需的结果。


此外,正如我最终发现的 duplicate 所指示的那样,要简单地将所有居中,您可以使用 TextImageRelation 并将其设置为 TextImageRelation.ImageBeforeText 而不更改对齐方式,如有必要,可以增加根据显示图像的大小调整高度以获得干净的结果:

enter image description here

enter image description here