如何在PictureBox控件上创建彩色边框?

时间:2010-12-15 03:40:16

标签: c#

我在PictureBox1.Image属性中有一个PictureBox和一个图像 如何在图像周围放置边框?

5 个答案:

答案 0 :(得分:6)

您无法设置PictureBox边框的大小和颜色 但你可以做一点技巧来实现这一目标。

将图片设置为BackgroundImage属性 将BackgroundImageLayout设置为CenterBackColor属性更改为您想要边框的颜色 现在调整PictureBox的大小以显示背面颜色,现在在视觉上就像边框一样。

您还可以使用Padding属性完成最后一步。

希望有所帮助。

答案 1 :(得分:3)

这一直是我用来做的:

要更改边框颜色,请从Picturebox控件的Paint事件处理程序中调用它:

private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {
        ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
    }

要动态更改边框颜色,例如从鼠标点击事件,我使用图片框的Tag属性来存储颜色并调整图片框的Click事件以从那里检索它。例如:

if (pictureBox1.Tag == null) { pictureBox1.Tag = Color.Red; } //Sets a default color
  ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, (Color)pictureBox1.Tag, ButtonBorderStyle.Solid);

图片框点击事件,然后会是这样的:

private void pictureBox1_Click(object sender, EventArgs e)
        {
            if ((Color)pictureBox1.Tag == Color.Red) { pictureBox1.Tag = Color.Blue; }
            else {pictureBox1.Tag = Color.Red; }
            pictureBox1.Refresh();
        }

您在开始时需要using System.Drawing;,不要忘记在结尾处致电pictureBox1.Refresh()。享受!

答案 2 :(得分:2)

您可以通过继承System.Windows.Forms.PictureBox并覆盖PictureBoxOnPaint方法来创建自己的PictureBox,从这里使用System.Windows.Forms.ControlPaint类来绘制自定义边框' DrawBorder'方法并传入你的System.Windows.Forms.PaintEventArgs'来自' OnPaint'方法

像这样;

using System.Windows.Forms;
using System.Drawing;

public class CustomPictureBox : PictureBox
{
  protected override void OnPaint(PaintEventArgs e) 
  {
    base.OnPaint(e);
    ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, Color.Red, ButtonBorderStyle.Solid);
  }
}

这只是一个快速的例子(未经测试)让你开始,抱歉我不能更彻底。

答案 3 :(得分:0)

我在这里因为我遇到了同样的问题。我指出了一个更简单的解决方案,那就是。

  1. label后面放置一个picturebox
  2. label的背景颜色更改为所需边框的颜色。
  3. label的{​​{1}}媒体资源设为AutoSize并根据需要调整false的大小。
  4. 样品:

    enter image description here

答案 4 :(得分:0)

为了实现这一目标,我使用了带有背景图像的按钮并设置了FlatApparence属性

相关问题