对于初学者来说,如果您使用的是WinForms,您可以通过重写OnPaint方法并将控件样式设置为手动绘制来获取图形对象。像这样
... .ctor()
{
...
// indicate user will paint
SetStyle(ControlStyles.UserPaint, true);
// rest is optional if you want/need it
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.Opaque, true);
}
protected override void OnPaint(PaintEventArgs p)
{
// depending on how you set the control styles, you might need
// this to draw the background of your control wit a call to the methods base
base.OnPaint(p);
Graphics g = p.Graphics;
// ... Do your painting here with g ....
}
但是,既然您也将此问题标记为WPF,请注意,这不适用于wpf。我在这个主题上并不是很先进,但是我已经使用了UIElement.OnRender方法的重写并取得了很好的结果。它会给你一个DrawingContext对象,而不是PaintEventArgs对象。但他们的工作方式大致相同。另外你不需要设置控制风格。
您是否收到编译器错误或运行时错误。如果是这样,你是什么? – fluent