tigger
tigger

Reputation: 1906

How to clone a Graphics in C#?

I want to provide different parts of an application with independent Graphics instances which end up painting on the same base Graphics. Simply cloning the Graphics works, but since both instances refer to the same GDI handle, there are not independent. I can't use Begin and EndContainer as well since I have a method which has to provide the new Graphics instances. -so I cannot determine when to call EndContainer. The use case is quite similar to the Graphics.create() method in Java.

I've found some workarounds, but none of them works for a Graphics provided by the PrintController.

Is there any proxy-Graphics I can use? Or is there a possibility to create another Graphics for the same device for instance?

Upvotes: 1

Views: 3505

Answers (5)

amr osama
amr osama

Reputation: 1159

I was facing same problem, I found the only solution is to duplicate the drawings code line !!

Like the following:

 e.Graphics.DrawString(points(i).pointText, myFont, Brushes.Blue, New Point(points(i).crossPointX4, points(i).crossPointY4)) : G.DrawString(points(i).pointText, myFont, Brushes.Blue, New Point(points(i).crossPointX4, points(i).crossPointY4))

Upvotes: 0

Tom
Tom

Reputation: 3374

Graphics objects are not meant to be persisted. You could use a backbuffer approach by drawing to a Bitmap before your final render.

Perhaps you could raise an event to which listening drawing components could subscribe, and your calling code could chain these together. That way you could use the same Graphics instance without compromising GDI efficiency.

Upvotes: 1

codymanix
codymanix

Reputation: 29490

A possibility would be to create multiple graphics objects which are pointing to multiple targets, for example an memory image. Then after done, combine all images into one.

But the thing I don't understand is, if all graphics instances should paint to the same target why do you need multiple graphics objects in the first place?

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942020

This sounds bad. Do not store references to a Graphics object, it only ever lives temporarily and is only valid while a Paint or PrintPage event handler is running. Do make sure to pass it as an argument to whatever method does the drawing instead of storing it in a field or a global variable.

If the method is altering the state of the object then use the Save() and Restore() methods to prevent this from causing problems in subsequent methods that use that same object. Cloning it is never necessary with this approach.

Upvotes: 3

Doggett
Doggett

Reputation: 3464

Not sure what exactly you're trying to do but you can use CreateGraphics() on a Control or Graphics.FromImage(xx) to create a new Graphics object for the control and/or image. There's also a few more functions in Graphics.FromXXX

Upvotes: 0

Related Questions