【发布时间】:2014-09-05 11:25:28
【问题描述】:
当设置Button.Image 属性时,Button 周围出现不需要的边框。第二张图片是光标在黄色框上时。
当 button.ImageAlign 设置为 ContentAlingment.MiddleCenter 时,边框仍然存在,但宽度为 1 个像素。
红框应为 100x100,但为 95x95(在屏幕截图上测量)。
预期结果是四个正方形,中间没有间隙。
当我使用BackgroundImage 属性时问题不存在,但禁用时按钮不会自动变灰。
完整代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Shown += OnShown;
}
private Bitmap DrawFilledRectangle(int x, int y, Brush brush)
{
var bmp = new Bitmap(x, y);
using (var graph = Graphics.FromImage(bmp))
{
var imageSize = new Rectangle(0, 0, x, y);
graph.FillRectangle(brush, imageSize);
}
return bmp;
}
private void OnShown(object sender, EventArgs eventArgs)
{
BackColor = Color.Wheat;
var leftTop = new Button();
var rightTop = new Button();
var leftBottom = new Button();
var rightBottom = new Button();
var bmp1 = DrawFilledRectangle(100, 100, Brushes.Firebrick);
var bmp2 = DrawFilledRectangle(100, 100, Brushes.ForestGreen);
var bmp3 = DrawFilledRectangle(100, 100, Brushes.CornflowerBlue);
var bmp4 = DrawFilledRectangle(100, 100, Brushes.Yellow);
SetButton(leftTop, bmp1);
SetButton(rightTop, bmp2);
SetButton(leftBottom, bmp3);
SetButton(rightBottom, bmp4);
leftTop.Left = leftTop.Top = 10;
rightTop.Left = leftTop.Left+ bmp1.Width;
rightTop.Top = 10;
leftBottom.Left = 10;
leftBottom.Top = leftTop.Top + bmp1.Height;
rightBottom.Left = leftBottom.Left + bmp1.Width;
rightBottom.Top = rightTop.Top + bmp1.Height;
Controls.AddRange(new Control[] { leftTop, rightTop, leftBottom,rightBottom });
}
private void SetButton(Button button, Bitmap bmp)
{
button.FlatAppearance.BorderColor = Color.FromArgb(0, 0, 0, 0);
button.FlatAppearance.BorderSize = 0;
button.FlatStyle = FlatStyle.Flat;
button.Image = bmp;
button.ImageAlign = ContentAlignment.TopLeft;
button.Margin = new Padding(0);
button.Padding = new Padding(0);
button.Size = bmp.Size;
}
}
编辑
我在实际应用中有图片而不是填充框。
【问题讨论】:
-
如果您不希望控件像按钮一样作用,那么就不要使用按钮控件。如果您改用 PictureBox,则可以删除很多代码。仍然有一个 Click 事件,显示一个带有 BackColor 属性的填充矩形,但没有悬停和聚焦行为。
-
但是我想要按钮和图片框。他们做得很好,只是看起来不太好。