Reputation: 11252
I have a custom control that is displaying a canvas image. I'm using AutoScroll and also a zoom ratio to display the image.
Therefore the data I have to work with are:
I need to calculate the Viewport at any given time, given in coordinates relative to the original bitmap. So if the entire image is visible, and the image is 800x600, then the Viewport would be a Rectangle at 0,0 with a size of 800,600.
I'm zoomed on the image, the Viewport should always be the rectangle representing the entire visible area. If I'm zoomed out and the image is centered on the screen then the viewport should be the entire image.
EDIT: Here is a graphical representation. The bitmap is currently zoomed, but I have the original size and the ratio at which it is zoomed. And I have the AutoScrollPosition. The AutoScrollMinSize is set depending on the zoom level. If the image height is 500px and we're at 200% (2.0f) zoom, then the AutoScrollMinSize.Height is 1000.
The red box would represent the Viewport rectangle.
Upvotes: 1
Views: 1953
Reputation: 11252
I figured it out. Here is the code that I got to work for me.
In this solution, AutoScrollMinSize is equal to CanvasBounds.Size. First I check if the window is bigger than the canvas, in which case I know the entire bitmap is visible and return that as the viewport. Otherwise, I calculate it by converting the screen pixels to bitmap pixels.
public RectangleF Viewport
{
get
{
if (AutoScrollMinSize.Width <= ClientRectangle.Width && AutoScrollMinSize.Height < ClientRectangle.Height)
{
return BitmapRectF;
}
else
{
return new RectangleF(
Math.Abs(AutoScrollPosition.X / _ratio),
Math.Abs(AutoScrollPosition.Y / _ratio),
Math.Min(CanvasBounds.Width / _ratio, ClientRectangle.Width / _ratio),
Math.Min(CanvasBounds.Height / _ratio, ClientRectangle.Height / _ratio)
);
}
}
}
Upvotes: 0