From your code sample, it looks like you generally understand the idea. This sample has many problem, so you need to put it all in order.
First, please see my past answer on graphics rendering related to
OnPaint
:
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
capture the drawing on a panel[
^],
Drawing Lines between mdi child forms[
^],
on zooming:
Zoom image in C# .net mouse wheel[
^],
references:
How to avoid Red Cross in DatagridView C#[
^].
First of all, you don't need
PictureBox
, it is not helpful, would only add hassles to your work.
You don't need
UserControl
with is only needed to support the designer. Your base class can be
System.Windows.Forms.Control
, or some other suitable control, like
Panel
. As you can see,
OnPaint
call is indirectly rendered via the call to
Invalidate
. You can invalidate not the whole scene, but a part of it, rectangle or path.
OnPaint
does one thing: renders some data model of the view using
Graphics
passed in the event arguments parameter.
What is your model? First of all, for reasonable performance, you have to have two images: magnified and "normal". Of course, you can re-sample of from another programmatically, but never go from smaller size to bigger size: your source image should always be the bigger one, otherwise you can badly screw up image quality. Scaling up is not what can work well, because you don't have data for the pixels added. Anyway, make sure your re-sampling is made only once, not on each click.
Then your model should include the location of the magnified area, its size, shift between magnified and "normal" bitmap. And, finally, it should be a Boolean flag showing if the magnification is on or off. Let's say, you calculate it from the mouse clicks, which also call
Invalidate
.
Your
OnPaint
takes the model data and, depending on data, draw one or two layers. First you draw the unmagnified image. Then, if magnification mode is on, you crop magnified image and draw this part on top. Make sure to switch "optimized double buffering" on, otherwise you would get nasty flicker. That's all.
Non-rectangular magnified are will take a lot more processing. And if this area is a round, it would be much better than if it is more complicated. If you want to go this way, ask your question; I'll try to answer.
—SA