c# - 在偏移处绘制图形

标签 c# graphics

在我的代码中,假设我有 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)
  }
}

最佳答案

Graphics 对象上设置一个转换:

protected override void OnPaint(PaintEventArgs e) 
{
    Graphics g = e.Graphics;

    Matrix transformation = new Matrix();
    transformation.Translate(50, 50);

    g.Transform = transformation;
}

protected override void OnPaint(PaintEventArgs e) 
{
    Graphics g = e.Graphics;
    g.TranslateTransform(50, 50);
}

关于c# - 在偏移处绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854859/

相关文章:

c# - 结构图 : How to setup for Specific Concrete Instance of Interface to use particular CTOR

c# - Entity Framework 非常慢

OpenGL多个Sampler2D(数组)示例?

c++ - 向继承自 QGraphicsScene 的类添加信号

c# - 如果两个字段不匹配,则将新行插入数据库表,否则在特定列中求和值

c# - .Net 核心依赖注入(inject) IdbConnection

c# - 以另一种形式存储数据保护问题

java - JFrame 不显示 Canvas

graphics - 以 2D 矢量格式从 Pov-Ray 转换/导出图形

Python 在 Mac 上崩溃