Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw graphics at offset

Tags:

c#

graphics

In my code, let's say I have the PaintObject(Graphics g). In some other function, I want to call the PaintObject function to draw something at an offset, instead of drawing it at (0,0).

I know that in Java, I could use the Graphics.create(x, y, width, height) function to create a copy of my graphics object which I could use, which would draw within those bounds of the original graphics. Is there a way to do something similarly in C#?

Just to give you an example of what my code could look like:

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)
  }
}
like image 733
Frxstrem Avatar asked Mar 24 '12 19:03

Frxstrem


2 Answers

Set a transformation on the Graphics object:

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

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

    g.Transform = transformation;
}

or

protected override void OnPaint(PaintEventArgs e) 
{
    Graphics g = e.Graphics;
    g.TranslateTransform(50, 50);
}
like image 122
tbridge Avatar answered Sep 27 '22 23:09

tbridge


Use the Graphics method

public void TranslateTransform(float dx, float dy)

g.TranslateTransform(dx, dy);
like image 40
Olivier Jacot-Descombes Avatar answered Sep 27 '22 22:09

Olivier Jacot-Descombes