【发布时间】:2018-09-05 04:21:23
【问题描述】:
我正在创建一个自定义图片框。
如您所见,它是专为个人资料照片设计的 PictureBox
嗯,这是 CircularPictureBox 的类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Hector.Framework.Controls
{
public class CircularPictureBox : PictureBox
{
private Color _idlecolor = Color.White;
public CircularPictureBox()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
this.DoubleBuffered = true;
this.BackColor = Color.White;
this.SizeMode = PictureBoxSizeMode.StretchImage;
this.Size = new Size(100, 100);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
using (var gpath = new GraphicsPath())
{
var brush = new SolidBrush(this.IdleBorderColor);
var pen = new Pen(brush, 5);
var outrect = new Rectangle(-1, -1, this.Width + 5, this.Height + 5);
gpath.AddEllipse(outrect);
pe.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
pe.Graphics.DrawPath(pen, gpath);
brush.Dispose();
pen.Dispose();
gpath.Dispose();
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
using (var gpath = new GraphicsPath())
{
var rect = new Rectangle(1, 1, this.Width - 1, this.Height - 1);
gpath.AddEllipse(rect);
this.Region = new Region(gpath);
gpath.Dispose();
}
}
public Color IdleBorderColor
{
get => this._idlecolor;
set => this._idlecolor = value;
}
}
}
我的问题是,由于它是一个可以从设计器中使用的控件,我希望它具有边缘宽度或边框颜色等属性。
我开始用颜色进行测试,但每当我改变颜色时, Visual Studio 向我显示一条错误消息,指出 属性的值无效
【问题讨论】:
-
嗯,你输入的哪些值是无效的?
-
@ForeverZer0 在 Visual Studio 设计器中,由我的 IdleColor 创建的属性通过更改颜色向我显示此消息
-
我可以看到一个讨厌的错误,不要在绘制事件中分配 Region 属性。副作用太多,它会导致油漆再次燃烧,你会看到 VS 燃烧 100% 核心。它属于 OnResize()。这也会炸毁你的代码,因为你忘记在笔和画笔上调用 Dispose(),显示在 5000 次绘画后结束,反过来导致 VS 变得非常不安。
-
在调用 method_0 之前检查设计模式。 (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
-
首选不设置
Region。如果将区域设置为圆形区域,您将看到图片框周围出现锯齿状边框,而您可以使用SetClip到圆形路径来强制控件将自身绘制成圆形。然后对于透明效果,只需将颜色设置为Color.Transparent。要查看这两种情况的示例,请查看this post。
标签: c# winforms graphics picturebox