Giter Site home page Giter Site logo

cyotek / cyotek.windows.forms.imagebox Goto Github PK

View Code? Open in Web Editor NEW
179.0 31.0 74.0 19.93 MB

The ImageBox is a custom control for displaying images. It supports zooming, scrolling, panning, region selection and much more!

Home Page: http://cyotek.com/blog/tag/imagebox

License: MIT License

C# 98.48% CSS 1.32% Batchfile 0.20%
cyotek imagebox c-sharp winforms-controls hacktoberfest

cyotek.windows.forms.imagebox's Introduction

Cyotek ImageBox Control

About

The ImageBox is a lightweight owner drawn control for displaying images. It supports zooming, scrolling, panning, region selection and much more! In addition to the traditional mode of binding to an Image, you can also use a virtual mode, and provide your own custom drawing whilst retaining all the ImageBox functionality.

The ImageBox control also provides convenient helper methods for translating points, rectangles and sizes according to the current zoom level and scroll position of the control - this makes it easy to scale custom drawing to fit the control.

As well as the different behaviours offered, the ImageBox also supports a large number of display properties. The background of the control can display a solid colour, or a coloured grid in various sizes. You can also configure how the grid is to be drawn, for example just around the image bounds, or the full control bounds. Other options include the pixel grid, which is displayed when zooming in on an image to highlight each pixel, custom border styles for surrounding the image, and many other properties. You can also display text, and specifying formatting and alignment options.

Example Screenshots

ImageBox control demonstration

Virtual mode demonstration, where the ImageBox can be used without a backing image

The ImageBox can display a pixel grid when zooming in

License

The ImageBox control is licensed under the MIT License. See license.txt for the full text.

Further Reading

For more information on this control, see the articles tagged withimagebox at cyotek.com.

cyotek.windows.forms.imagebox's People

Contributors

cyotek avatar dahmage avatar fruchtzwerg94 avatar teamalpha5441 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cyotek.windows.forms.imagebox's Issues

Drag test - out of bounds error

Was trying the Demo project that is shipping with the control and noticed in the Drag test that if I exit the yellow area (with the mouse button still pushed) the blue box resets to position (0, 0) inside the yellow area. Maybe it would be best not to set it to (0, 0) but to leave it at the last position before the mouse cursor left the yellow area.

VirtualDraw and Scale\Transform

First off - Richard Great work!

I have some print code that I would love to have as a form component.
The Print routine now currently assumes Width, Length and Scale to deal with Letter vs A4 and 300 vs 600 DPI in printers. ie (ie RenderReport(g, 850,1100,100);

I can only render the whole page, so after I would like to Transform(x,y) to shift to the newer upper left and clip(x+w, y+h) the right and bottom based on the scale so that the rendered size is always the size of the Window while maintaining the aspect ratio.

I can get it to sort of work, but the scroll bars are screwed and the highlight a region is off?

Any Suggestions?
Thanks,
Mike

Double click Event

Hi
For ImageBox, i registered to MouseDoubleClick event, but for some reason event is not being raised.
however MouseClick (single click) event fires properly..
what could be the issue?

Thanks & Regards

Cache visible image portion for painting

Each time an ImageBox control paints itself, it goes through the job of picking part of the image, scaling it, and then painting it.

While this is normally fine, if you manually invalidate an image box repeatedly (for example when drawing custom adornments in reaction to user input), this can affect the responsiveness of the application.

It would probably be a better idea of the ImageBox control created a cached bitmap of the part of the image currently displayed and then used that for painting, and only invalidated this when the layout is impacted, e.g. scrolled, zoomed etc.

See this thread for a sample project I created which identified the issue.

Love ImageBox

Nice to see some work going into ImageBox. Love this little viewer. Keep up the good work @cyotek .

Memory issue

hi
i noticed a small bug when dynamically allocating imageBox to tableLayoutPanel and removing/clearing imageBox back
i tried in C++/Cli (Winforms)

in form load event i created tableLayoutPanel with 25 cells (5 rows, 5 column) in each cell i placed a new instance of imageBox. (i noticed a hike of 20 - 30mb in memory consumption in visual studio's diagnostic tool)

now, how to free memory occupied by imageBox, if i call TableLayoutPanel.Controls.Clear , this doesn't free up memory. so i have to call Dispose right?

can you expose Dispose func, because as of now it says Dispose cannot be called by pointer or object?

Note: closing form or calling System.GC.Collect frees up memory
Thank you

How to save viewport as bitmap?

Hi, i am overriding OnPaint and draw an overlay on my image.

Can I Somehow save that whole construct of Image + Overlay in a .BMP file?
When I use DrawToBitmap it renders only the visible part, but i want the whole part.

MouseWhell zoom or scroll

Hello,

I wish to do a zoom when pressing ctrl during mousewheel else a simple vertical scroll but i don't know how to modify the code. Can someone give me some steps please ?

I guess that i have to override onMouseWheel. Select depending if ctrl is pressed and use ProcessMouseZoom but protection is not accepted so i have a doubt. Is there any function to manage scroll too ?

Zoom value not always correct

When I show the Zoom value in the immediate window and I'm zooming in and out by using the mousewheel the value goes down when scrolling the mouse wheel down but when you scroll up again the first value first goes down and then it goes up. So suppose I'm zooming in and the zoom goes from 25, 30 50 and then at 70 I think oh thats to big so I go back wanting to go 50 but instead the value shows 100. It looks as if the directions the first time goes wrong.
I have tried the Mousewheel event and the ZoomChanged event and worked with latest v2.0.50727 version (but reproduced it also in older versions).
Thanks for looking into this.

Update: When I tried to break down the problem (which I should have before posting here ;-) it somehow solved the problem. Don't know what caused it. So never mind.

Unable to Crop image

This is an excellent and versatile control, I am using the ImageBoxEx code (v1.1) extending the ImageBox v1.4 found in the latest NuGet package. I am using ImageBoxEx because I want to add some image editing capabilities to transform my image.

So far I get my image displayed, the selection regions are displayed and can be resized and moved. At some point though, I want to CROP the image using the SelectionRegion rectangle. I have the code to do the cropping which I have tested in a regular (stock) PictureBox control; However, this does not seem to be working with the ImageBox/Ex controls.

Basically I do this:

using (ImageProcessor imgProc = new ImageProcessor(imageBox1.Image))
{
  Rectangle rect = Rectangle.Round(imageBox1.SelectionRegion);
  imageBox1.SelectNone();
  imgProcessor.Crop(rect);
  imageBox1.Image = imgProcessor.CurrentImage;
}

where the Crop method looks like this:

public void Crop(Rectangle r)
{
   Bitmap temp = (Bitmap)_currentBitmap;   // this is where the bitmap was placed by the constructor
   Bitmap bmap = (Bitmap)temp.Clone();
   if (r.X + r.Width > _currentBitmap.Width)
       r.Width = _currentBitmap.Width - r.X;
   if (r.Y + r.Height > _currentBitmap.Height)
       r.Height = _currentBitmap.Height - r.Y;
   _currentBitmap = (Bitmap)bmap.Clone(r, bmap.PixelFormat);
}

But after I do that the imageBox image gets cleared from the ImageBoxEx control. If I eliminate the using() then the image remains the same as if I had not cropped it.

Use 2 ImageBoxes side by side

I'd like to use 2 ImageBoxes next to each other in a TableLayoutPanel

If the ZoomChanged event of one of the two images is triggered, the zoom value must be added to the other ImageBox.
The same applies to the Scroll event.

Problem: The left image is always fluid, regardless of whether I scroll on this image or on the other, but the right image is always laggy.

I'm guessing this isn't a problem with the ImageBox component but with Windows Form in general, which can't update 2 components at the same time?

Is there nevertheless a workaround?

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Create both bitmaps

            //Left
            Bitmap left = new Bitmap(3000,3000); 
            Bitmap right = new Bitmap(3000, 3000);
            
            Graphics g = Graphics.FromImage(left);
            //Make light blue / blue pattern
            for (int x = 0; x < 3000; x += 500)
            {
                for (int y = 0; y < 3000; y += 500)
                {
                    g.FillRectangle(Brushes.LightBlue, x, y, 500, 500);
                    g.FillRectangle(Brushes.Blue, x + 250, y, 250, 250);
                    g.FillRectangle(Brushes.Blue, x, y + 250, 250, 250);
                }
            }

            //Make light green / green pattern
            g = Graphics.FromImage(right);
            for (int x = 0; x < 3000; x += 500)
            {
                for (int y = 0; y < 3000; y += 500)
                {
                    g.FillRectangle(Brushes.LightGreen, x, y, 500, 500);
                    g.FillRectangle(Brushes.Green, x + 250, y, 250, 250);
                    g.FillRectangle(Brushes.Green, x, y + 250, 250, 250);
                }
            }

            g.Dispose();

            imgBoxLeft.Image = left;
            imgBoxRight.Image = right;
        }
        //Event
        private void imgBoxLeft_Scroll(object sender, ScrollEventArgs e)
        {
            imgBoxRight.ScrollTo(imgBoxLeft.HorizontalScroll.Value, imgBoxLeft.VerticalScroll.Value);
        }

        private void imgBoxLeft_ZoomChanged(object sender, EventArgs e)
        {
            imgBoxRight.Zoom = imgBoxLeft.Zoom;
        }

        private void imgBoxRight_Scroll(object sender, ScrollEventArgs e)
        {
            imgBoxLeft.ScrollTo(imgBoxRight.HorizontalScroll.Value, imgBoxRight.VerticalScroll.Value);
        }

        private void imgBoxRight_ZoomChanged(object sender, EventArgs e)
        {
            imgBoxLeft.Zoom = imgBoxRight.Zoom;
        }
    }
Example.mp4

If you directly want to test, you can clone the test project: https://github.com/FrancoisBck/DualImageBox/tree/master

Image Alignment

Is there a way to align the image to the Left, Center, or Right side of the imageBox control? It seems to center by default.

Thanks,
Darren

How to determinate a pixel in the imageBox (Mouse click) with total precision

Hi all, I'm an Spanish programmer :3 and I'm using and enjoying the ImageBox library with Visual Studio 2015.

I'm trying to edit a very low resolution image (from 32 to 128px) using a high Zoom level (600 or above), and the first feature I need is to determinate (with total precision) which pixel Point has been clicked. I share with you the code and a screenshot with the results when I click on the marked (red cross) pixel.

I think I need to calculate the difference from the main window, to the margin, or something like this, but I'm tired of trying with no results and maybe the library has a method for this task. If anyone know what am I doing bad, or what could I try to do, I will be always grateful!

The screenshot, where you can see the Point is correctly obtained on very low and in total fit resolution, but has an error when zoom in (Look at the scrollbars, it is like if it ignore the offset):

https://imgur.com/5vFREeY

And the code:

`int zoom = this.imageBox.Zoom;
Control control = (Control)sender;
Point controlToScreen = control.PointToScreen(MousePosition);
Point mouseOffset = this.imageBox.GetOffsetPoint(MousePosition);
Point mouseScaled = this.imageBox.GetScaledPoint(MousePosition);
Point mouseToImage = this.imageBox.PointToImage(MousePosition);
Point mouseToClient = this.imageBox.PointToClient(MousePosition);
Point mouseToScreen = this.imageBox.PointToScreen(MousePosition);

        Point controlToScreenZoom = new Point(controlToScreen.X * 100 / zoom, controlToScreen.Y * 100 / zoom);
        Point mouseOffsetZoom = new Point(mouseOffset.X * 100 / zoom, mouseOffset.Y * 100 / zoom);
        Point mouseScaledZoom = new Point(mouseScaled.X * 100 / zoom, mouseScaled.Y * 100 / zoom);
        Point mouseToImageZoom = new Point(mouseToImage.X * 100 / zoom, mouseToImage.Y * 100 / zoom);
        Point mouseToClientZoom = new Point(mouseToClient.X * 100 / zoom, mouseToClient.Y * 100 / zoom);
        Point mouseToScreenZoom = new Point(mouseToScreen.X * 100 / zoom, mouseToScreen.Y * 100 / zoom);

        // Los métodos de conversión de punto tienen parámetros adicionales que faltan por probar
        this.lblDebugImageBox.Text = "ZOOM " + zoom + Environment.NewLine +
        "Screen clic " + MousePosition + Environment.NewLine +
            " form " + controlToScreen + Environment.NewLine +
            " offset " + mouseOffset + " scaled " + mouseScaled + Environment.NewLine +
            " point to image " + mouseToImage + Environment.NewLine +
            " point to client " + mouseToClient + Environment.NewLine +
            " point to screen " + mouseToScreen + Environment.NewLine +
            Environment.NewLine +
            " form with zoom " + controlToScreenZoom + Environment.NewLine +
            " offset withzoom " + mouseOffsetZoom + " scaled " + mouseScaledZoom + Environment.NewLine +
            " point to image with zoom " + mouseToImageZoom + Environment.NewLine +
            " point to client withzoom " + mouseToClientZoom + Environment.NewLine +
            " point to screen withzoom " + mouseToScreenZoom + Environment.NewLine;`

Use of SystemInformation.MouseWheelScrollDelta within MouseWheel event for Zooming

Hi,

I want to bring attention to the usage of SystemInformation.MouseWheelScrollDelta which cannot be relied upon.

It causes an issue where cannot Zoom without scrolling the mouse wheel a lot because there are mice that have a different delta constant to what is given by SystemInformation.MouseWheelScrollDelta.

The mouse I have right now has a delta of 30 but SystemInformation.MouseWheelScrollDelta is 120.

The code where issue is:

       int spins;

        // The MouseWheel event can contain multiple "spins" of the wheel so we need to adjust accordingly
        spins = Math.Abs(e.Delta / SystemInformation.MouseWheelScrollDelta);

        // TODO: Really should update the source method to handle multiple increments rather than calling it multiple times
        for (int i = 0; i < spins; i++)
        {
          this.ProcessMouseZoom(e.Delta > 0, e.Location);
        }

One way to fix the issue is to keep a remainder of delta / SystemInformation.MouseWheelScrollDelta and make sure to reset the remainder to 0 if scroll direction changes or scrolling stops (after a period of time has passed).

I have put together code changes for the above fix. The code has been tested and the fix is working.


    private const int MouseWheelScrollDeltaRemainderResetDelay = 250;
    private int _mouseWheelScrollDeltaRemainder;
    private int _mouseWheelScrollDeltaUpdateTime;

    protected override void OnMouseWheel(MouseEventArgs e)
    {
      base.OnMouseWheel(e);

      if (this.AllowZoom && this.SizeMode == ImageBoxSizeMode.Normal)
      {
        // A remainder is kept so can support mice that use a  delta value that isn't SystemInformation.MouseWheelScrollDelta
        // for the mouse wheel.
        //
        // The remainder will also be reset to 0 after a time delay to prevent it affecting future scrolling where user stops
        // scrolling and then comes back and starts scrolling again. In that case we want the remainder to start at 0 again.
        //
        // To detect the switching of scroll direction will simply just check the sign of delta and delta remainder.
        // Then can reset the remainder to 0 because do not want the scrolling in different direction to affect the current direction.
        int delta = e.Delta + this._mouseWheelScrollDeltaRemainder;

        if (Environment.TickCount - this._mouseWheelScrollDeltaUpdateTime > MouseWheelScrollDeltaRemainderResetDelay ||
            (delta < 0) != (this._mouseWheelScrollDeltaRemainder < 0))
        {
          this._mouseWheelScrollDeltaRemainder = 0;
        }

        this._mouseWheelScrollDeltaRemainder = delta % SystemInformation.MouseWheelScrollDelta;
        this._mouseWheelScrollDeltaUpdateTime = Environment.TickCount;

        int spins;

        // The MouseWheel event can contain multiple "spins" of the wheel so we need to adjust accordingly
        spins = Math.Abs(delta / SystemInformation.MouseWheelScrollDelta);

        // TODO: Really should update the source method to handle multiple increments rather than calling it multiple times
        for (int i = 0; i < spins; i++)
        {
          this.ProcessMouseZoom(e.Delta > 0, e.Location);
        }
      }
    }

Default zoom level option

There is "SizeMode" property. If you set it to "Fit", you cannot scroll or zoom the picture. If you set it to "Normal", you can scroll or zoom the picture, but when the picture is first loaded, if the image is big, only a portion of it shows with scroll bars.
I tried to call ZoomToFit() right after changing the Image, but then there is the split-second flickering of the image resizing (normal -> fit).
It would be helpful if in "Normal" "SizeMode", there was an option to make the image fit the control when first set. Most image viewer programmes I have used worked this way; they allowed zoom, but when the image is first loaded it fits the window.

Problem when trying to hide Scrollbar

Hello,

Thank for your project.
I got an issue. I tried to hide scrollbar (both vertical and horizontal bar) of ImageBox:

imageBox.AutoScroll = false;
imageBox.VerticalScroll.Visible = false;
imageBox.HorizontalScroll.Visible = false;

The problem occurred when I use zoom function. Zoomed image was run to above and disappear!

loi

Zoom after Stretch and ScrollBars

Hi

i'm not sure if its intentional made not to zoom, if SizeMode is not Normal
once i change Size Mode to Stretch or Fit zoom doesn't work

i was trying out this control, where i changed Dock : Fill and SizeMode: Stretch for image to fit within resizable winform. but how can be enable zoom after this ?
also is it possible to hide scrolls bars while maintaining image to be at center (AutoCenter : True)?

Thanks

Update: below code didn't work!

imageBox.HorizontalScroll.Visible = false;
imageBox.VerticalScroll.Visible = false;

Swipe support?

I am using the ImageBox control for my (non-commercial) picture viewer application.
It works great and was fairly easy to implement (once I discovered that Image objects have to be "Dispose"d to avoid memory overflow).
It would be nice to get swipe support, even under Windows 7.
Currently, I navigate between the pictures via mouse clicks.

Any hints or ideas?

Pixel grid replacement on common grid with grid autoscale and minor and major lines

    protected virtual void DrawPixelGrid2(Graphics g)
    {
      float gridSize;


      Rectangle imageViewport = this.GetImageViewPort();
      int smallGridFillFactor = 1;


      if ((float)this.ZoomFactor <= 0.5f)
        smallGridFillFactor = 100;
      else if ((float)this.ZoomFactor <= 5)
        smallGridFillFactor = 10;
      else if ((float)this.ZoomFactor > 5)
        smallGridFillFactor = 1;

      float smallGridCell = (float)this.ZoomFactor * smallGridFillFactor;

      int largeGridFillFactor = smallGridFillFactor * 10;
      float largeGridCell = (float)this.ZoomFactor * largeGridFillFactor;


      float smallGridoffsetX = Math.Abs(this.AutoScrollPosition.X) % smallGridCell;
      float smallGridoffsetY = Math.Abs(this.AutoScrollPosition.Y) % smallGridCell;

      float largeGridoffsetX = Math.Abs(this.AutoScrollPosition.X) % largeGridCell;
      float largeGridoffsetY = Math.Abs(this.AutoScrollPosition.Y) % largeGridCell;
      Debug.WriteLine(string.Format("Small GridCell: {0}", smallGridCell));
      Debug.WriteLine(string.Format("Large GridCell: {0}", largeGridCell));

      Pen majorPen = GetMajorPen();
      Pen minorPen = GetMinorPen();


      for (float x = imageViewport.Left - smallGridoffsetX; x < imageViewport.Right; x += smallGridCell)
      {
        g.DrawLine(minorPen, x, imageViewport.Top, x, imageViewport.Bottom);
      }
      for (float y = imageViewport.Top - smallGridoffsetY; y < imageViewport.Bottom; y += smallGridCell)
      {
        g.DrawLine(minorPen, imageViewport.Left, y, imageViewport.Right, y);
      }


      for (float x = imageViewport.Left - largeGridoffsetX; x < imageViewport.Right; x += largeGridCell)
      {
        g.DrawLine(majorPen, x, imageViewport.Top, x, imageViewport.Bottom);
      }
      for (float y = imageViewport.Top - largeGridoffsetY; y < imageViewport.Bottom; y += largeGridCell)
      {
        g.DrawLine(majorPen, imageViewport.Left, y, imageViewport.Right, y);
      }

      g.DrawRectangle(minorPen, imageViewport);


      majorPen.Dispose();
      minorPen.Dispose();
      return;
    }

Multiple Text

Hi.
i wanted to display a text with transparent background on video (using imageBox)
if i use a label and set its background to transparent and make parent = ImageBox then it flickers a bit (performance issues)
I know ImageBox has 'Text' field that's amazing, it works well.
but can we add multiple text at different locations?

Thanks & Regards
Prakash

Wrong selection area when maximizing

I was playing around with your control, and I faced inconsistent behavior when a region of the image is selected, and the windows is then maximized.
If the container window is maximized via a double click in the title bar, the selection area is messed up; everything is correct if the window is maximized using "Maximize" button.

I tried to replicate this behavior in the provided demo, and actually "General Demonstration" shows the same problem

Steps to reproduce

  • Run the demo
  • Click on General Demonstration
  • Set "Selection Mode" to "Rectangle"
  • Select a region in the image
    • look at the values in the lower right corner
  • Maximize the window using "Maximize" button
    • look at the values in the lower right corner: they are still correct
  • Restore the previous size, using the same button
    • look at the values in the lower right corner: they are still correct
  • Maximize the window, this time double-clicking in the title bar
    • look at the values in the lower right corner: they are now wrong
    • selected region is no longer shown in the lower pan

Selection(Marking) with 4 points

Hi
In General Demonstration, i chose SelectionMode : Rectangle. it works well.
i was wondering if it is possible to mark 4 points to define a rectangle (thought of rotating the rectangle by 45 degrees)

Once user chooses 4 points on Image, giving option to altering(dragging) any of 4 point's position will give preciseness for selection.

Thanks

Image graphics disappear when zooming out

Hi there,

I have a System.Drawing.Bitmap image with some painted graphics on it.

I then add this bitmap image to the ImageBox.

System.Drawing.Bitmap imgWithGraphics;
...
draw some graphics on image
...
Cyotek.Windows.Forms.ImageBox Imgbox;
...
Imgbox.Image = imgWithGraphics;

When I zoom out via the ImageBox to the level where the bitmap is smaller than the boundary of the image box, the graphics on the image disappear. when I zoom in to the original level - the graphics appear back.

Is there a way to zoom out properly without loosing the graphics?

[Enhancements] MouseWheelBehaviour property (zoom or scroll)?

I visited cryotek.com web site, and found that someone had asked this, and you replied that it had already been asked in GitHub. But I could not find it here, and since it seems many people want it, I hope there was a simpler way.

I mean, instead of letting each user to implement it on their own, how about adding as simple property that changes the scrolling behaviour? Like,
Zoom: always zooms.
Scroll: always scrolls. To zoom, use Ctrl + wheel.
Auto: if the image width fits the control, but the height does not, then scrolls; otherwise, zoom.

Solution to: Exception 'Out of Memory' while drawing a big image

While load a big image, for example 15000*8000 pixels, DrawImage almost always throw an exception 'Out of Memeory'.

I tested a solution, which works very well. Its key point is to divide image into several small parts and then draw each part one by one.

The code as follow:

            int CountOfStepX = (int)Math.Round(srcPortion.Width / MaxDrawImageSidePixels + 0.5);
            int CountOfStepY = (int)Math.Round(srcPortion.Height / MaxDrawImageSidePixels + 0.5);

            float stepDstX = (int)(dstView.Width / CountOfStepX);
            float stepDstY = (int)(dstView.Height / CountOfStepY);
            float stepSrcX = (int)(srcPortion.Width / CountOfStepX);
            float stepSrcY = (int)(srcPortion.Height / CountOfStepY);
            for(int w=0;w< CountOfStepX;w++)
                for(int h=0; h<CountOfStepY;h++)
                {
                    rfDst = new RectangleF(dstView.X+ stepDstX*w, dstView.Y + stepDstY * h, stepDstX, stepDstY);
                    rfSrc=  new RectangleF(srcPortion.X+ stepSrcX *w, srcPortion.Y + stepSrcY * h, stepSrcX, stepSrcY);
                    Rectangle txtRect = new Rectangle((int)rfDst.X, (int)rfDst.Y, (int)rfDst.Width, (int)rfDst.Height);
                    g.DrawImage(this.Image, rfDst, rfSrc, GraphicsUnit.Pixel);
                }

Creating and Zooming Graphics

Hi,

I placed below code in constructor of form

using (Graphics g = imageBox1.CreateGraphics())
{
  Pen blackPen = new Pen(Color.Black, 3);
  int x1 = 100;
  int y1 = 100;
  int x2 = 500;
  int y2 = 100;
  g.DrawLine(blackPen, x1, y1, x2, y2);
}

it didn't create the line. However if i use paint event, it draws the line

private void imageBox1_Paint(object sender, PaintEventArgs e)
{
    Pen blackPen = new Pen(Color.Black, 3);
    int x1 = 100;
    int y1 = 100;
    int x2 = 500;
    int y2 = 100;
    e.Graphics.DrawLine(blackPen, x1, y1, x2, y2);
}
  1. is there a way to draw graphics from first method
  2. how to zoom graphics ? when i scroll only image scrolls, graphics on it stays in the same place. is there a way to scroll both Graphics and Image together?

Thanks & Regards
Prakash

Update: we can use combination of Graphics.TranslateTransform(float dx, float dy) and Graphics.ScaleTransform (float sx, float sy).

I was thinking of passing imagebox1.Zoom value into Graphics.ScaleTransform and Mouse location on picture in Graphics.TranslateTransform

so I tried to zoom the graphics by using imagebox1.Zoom in ImageBox ZoomChanged event , its not working well.

I wanted to temporarily draw this graphic ,Directly drawing on image is not an option ..
so I was trying to set a point/circle on picture at location x=50, y =50. not sure on which location in imageBox i need to place this point and properly handle zooming + panning of this point/circle(System.Drawing.Graphic)

when Pixel grid is on selection select area inside pixels

I add code to ProcessSelection() to change behavior

ProcessSelection()
...
h = h / (float)this.ZoomFactor;

          float x = RoundToMinorGrid(x);
          float y = RoundToMinorGrid(y);
          float w = RoundToMinorGrid(w);
          float h = RoundToMinorGrid(h);
...

    private float RoundToMinorGrid(float x)
    {
      int smallGridFillFactor = 1;
      if ((float)this.ZoomFactor <= 0.5f)
        smallGridFillFactor = 100;
      else if ((float)this.ZoomFactor <= 5)
        smallGridFillFactor = 10;
      else if ((float)this.ZoomFactor > 5)
        smallGridFillFactor = 1;

      int mod = (int)x % smallGridFillFactor;
      float xx = x - mod + Math.Min(Math.Max(mod - smallGridFillFactor / 2, 0), 1) * smallGridFillFactor;
      return xx;
    }

Сan't distinguish click and panning event

Hi there!

Starting from version 1.3.0, events for a panning image began to work strangely.
With a normal click (cursor coordinates do not change), events occur in the following order:

  1. PanStart
  2. Click
  3. PanEnd

When I work with panning image the value of the property IsPanning is always true, because during the click PanStart event is always raised before OnClick event (even during a simple click when cursor coordinates do not change).

In versions prior to 1.3.0, there were no events before the click.

131
121

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.