在我的代码中,假设我有PaintObject(Graphics g).在其他一些函数中,我想调用PaintObject函数在偏移处绘制一些东西,而不是在(0,0)处绘制它.
我知道在Java中,我可以使用该Graphics.create(x, y, width, height)函数来创建我可以使用的图形对象的副本,它将在原始图形的那些边界内绘制.有没有办法在C#中做类似的事情?
只是为了举例说明我的代码可能是什么样子:
class MyClass : UserControl {
void PaintObject(Graphics g) {
// Example: draw 10x10 rectangle
g.DrawRectangle(new Pen(Color.Black), 0, 0, 10, 10);
}
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
// TODO: Paint object from PaintObject() at offset (50, 50)
}
}
Run Code Online (Sandbox Code Playgroud)
在Graphics对象上设置转换:
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
Matrix transformation = new Matrix();
transformation.Translate(50, 50);
g.Transform = transformation;
}
Run Code Online (Sandbox Code Playgroud)
要么
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.TranslateTransform(50, 50);
}
Run Code Online (Sandbox Code Playgroud)
使用Graphics方法
public void TranslateTransform(float dx, float dy)
Run Code Online (Sandbox Code Playgroud)
g.TranslateTransform(dx, dy);
Run Code Online (Sandbox Code Playgroud)