I am trying to use a C# port of TwoDScrollView in a Xamarin/Android project.
It works fine. We are adding scale gesture (we are showing an image that can be zoomed in/out by the user). That works fine as well.
The issue is that TwoDScrollView relies on ImageView.Width and ImageView.Height to make its calculation and that does NOT change - causing problems when trying to scroll after scaling. On resizing we are doing:
fullscreenImageView.ScaleX = _scaleFactor;
fullscreenImageView.ScaleY = _scaleFactor;
var lp = fullscreenImageView.LayoutParameters;
lp.Width = (int) (fullscreenImageView.Drawable.IntrinsicWidth * _scaleFactor);
lp.Height = (int) (fullscreenImageView.Drawable.IntrinsicHeight * _scaleFactor);
fullscreenImageView.RequestLayout (); //the request layout was just a test,
// it doesn't work either way
We can see how the layoutparameter width and height change, but the View.Width and View.Height never change... it is always the dimensions of the original image we loaded. How can we make that update? (one solution is to scale the bitmap and assign it to the imageview, but that's lousy and slow).
thanks.
According to this answer you should be able to set the dimensions of an ImageView object like this
image_view.getLayoutParams().width = (int) (fullscreenImageView.Drawable.IntrinsicWidth * _scaleFactor);
image_view.getLayoutParams().height = (int) (fullscreenImageView.Drawable.IntrinsicHeight * _scaleFactor);
where image_view is a reference to the same ImageView instance that your TwoDScrollView is looking to for dimensions.
Assuming your fullscreenImageView extends ImageView you can add this method in your fullscreenImageView
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
Related
I have a PictureBox inside a Panel, and I have implemented the zoom function with a TrackBar.
When I increase (or decrease) the PictureBox, the position of the image remain fixed on the left side of the PictureBox.
See the example to better understand the problem.
What I want is the possibility to relocate the image compared to the center of the Panel. See the following example
For example I tried to define the PictureBox X origin in this way:
before the zoom I calculate the distance (Δdx) between the origin of the PictureBox (x0) and the center of the Panel (x1).
I increase the distance with the zoom factor (Δdx').
I calculate the new origin of the image (x0') as x1 - Δdx'
I do the same with Y and I define the new PictureBox location with x0' and y0'.
Here the code:
// new image width after the zoom
double width = pbImg.Image.Width + (pbImg.Image.Width * trackbar.Value / 100);
// new image height after the zoom
double height = pbImg.Image.Height + (pbImg.Image.Height * trackbar.Value / 100);
// panel center
int cX = panel.Width / 2;
int cY = panel.Height / 2;
// actual origin for the picturebox
int imgX = pbImg.Location.X;
int imgY = pbImg.Location.Y;
// distance the panel center and the picturebox origin
int distFromXc = cX - imgX;
int distFromYc = cY - imgY;
// new distance with zoom factor
distFromXc = distFromXc + (distFromXc * trackbar.Value / 100);
distFromYc = distFromYc + (distFromYc * trackbar.Value / 100);
// new origin point for the picturebox
int pbX = (cX - distFromXc);
int pbY = (cY - distFromYc);
// new dimension for the picturebox
pbImg.Size = new Size(Convert.ToInt32(width), Convert.ToInt32(height));
// relocate picturebox
Point p = new Point(pbX, pbY);
pbImg.Location = p;
I tried to modify this C# code, but I’m not familiar with it.
In my case I want to manage the Picturebox and the image inside it as the same object (if it’s possible).
What I want is the possibility to increase (or decrease) the Picturebox (and the image inside) but I want the Picturebox to stay centered where it currently is.
The SizeMode of the picture is StretchImage.
The Trackbar has 0% as he minimum value and 100% as the maximum.
The size of the Picturebox, and the image isnside, can be variable, I receive the images from another software.
A zoomed Picturebox can be bigger than Panel, but it’s not a problem, because I can move it.
The problems are the following:
1. If i use the code I wrote above, the reposition seems to work, but the Picturebox isn’t resized.
2. If I use a fixed value for the origin of the Picturebox (for example Point p = new Point(50, 50)), the resize works but obviously the position of the Picturebox is fixed.
This is because you are changing the size of the picturebox and not the size of the image within it. To ensure an image matches the size of the picture box ensure you set the stretchimage sizemode
pbImg.SizeMode = PictureBoxSizeMode.StretchImage
to get it working you could add this line just before you change the size of the picture box, however i recommend setting this on picturebox during its creation.
Refer to : Fit Image into PictureBox
If you want the PictureBox to stay centered where it currently is, and only expand or deflate "in place", then try something like this:
double width = pbImg.Width * trackbar.Value / 100;
double height = pbImg.Height * trackbar.Value / 100;
Rectangle rc = pbImg.Bounds;
rc.Inflate((int)((width - pbImg.Width) / 2), (int)((height - pbImg.Height) / 2));
pbImg.Bounds = rc;
Note that this is all based on the size of the PictureBox itself, NOT the Image within. Not sure what SizeMode you have set for the PB...
---------- EDIT ----------
I'm using StretchImage as SizeMode. Is possible to have the same behavior but without the button? When I move the cursor from left to right the Pb increase and decrease from right to left – Scarj
Of course. Put my code into the ValueChanged() and/or Scroll() events. - Idle_Mind
The original post works off the current size of the PictureBox. You might want to store the original Bounds() of the PB (maybe in the Tag() property) and then always compute the new size based on that instead.
Here's an example of that:
private void Form1_Load(object sender, EventArgs e)
{
pbImg.Tag = pbImg.Bounds;
}
private void button1_Click(object sender, EventArgs e)
{
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
ZoomPB();
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
ZoomPB();
}
private void ZoomPB()
{
Rectangle rc = (Rectangle)pbImg.Tag;
double width = rc.Width * trackbar.Value / 100;
double height = rc.Height * trackbar.Value / 100;
rc.Inflate((int)((width - rc.Width) / 2), (int)((height - rc.Height) / 2));
pbImg.Bounds = rc;
}
I have found that this works PART of the time by inheriting the Windows Forms mouse point and subtracting out the height and width of my window to set the left and top (since my window's size is fixed):
MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();
System.Windows.Point mouseLocation = GetMousePositionWindowsForms();
window.Left = mouseLocation.X - 300;
window.Top = mouseLocation.Y - 240;
window.Show();
Edit: Here is the code for getting the mouse position...
public System.Windows.Point GetMousePositionWindowsForms()
{
System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
return new System.Windows.Point(point.X, point.Y);
}
Note that this works by making the bottom right edge of the window touch the top left of your mouse cursor. But this breaks for different screen resolutions, or maybe multiple monitors with different resolutiosn? I haven't fully narrowed it down yet, but I just tried this same code on another PC, and it seems to spawn the window not to the top left of the mouse cursor, but to the bottom left of it, and a good distance past it...
I should probably add that my window sizes to content, width and height, so I can't just use the ActualWidth and ActualHeight properties since they're not available. Perhaps the issue is in getting that sizing right? Is there any way to do that? I know for sure the 300 and 240 is correct according to my main PC with two monitors running 1920x1080 resolutions, as I have calculated the widths and heights of all the objects in my window which I have explicitly sized. Edit: Just tried explicitly setting the height and width to 240/300, to ensure that the window is no longer sized to content, and I still have this issue when subtracting out the actual height and width!
Any ideas?
In the end, this did the trick:
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
MoveBottomRightEdgeOfWindowToMousePosition();
}
private void MoveBottomRightEdgeOfWindowToMousePosition()
{
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());
Left = mouse.X - ActualWidth;
Top = mouse.Y - ActualHeight;
}
public System.Windows.Point GetMousePosition()
{
System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
return new System.Windows.Point(point.X, point.Y);
}
Can you not use something like this?:
Point mousePositionInApp = Mouse.GetPosition(Application.Current.MainWindow);
Point mousePositionInScreenCoordinates =
Application.Current.MainWindow.PointToScreen(mousePositionInApp);
I haven't been able to test it, but I think it should work.
UPDATE >>>
You don't have to use the Application.Current.MainWindow as the parameter in these methods... it should still work if you have access to a Button or another UIElement in a handler:
Point mousePositionInApp = Mouse.GetPosition(openButton);
Point mousePositionInScreenCoordinates = openButton.PointToScreen(mousePositionInApp);
Again, I haven't been able to test this, but if that fails as well, then you can find one more method in the How do I get the current mouse screen coordinates in WPF? post.
You can also do this by slightly modifying your initial example and positioning the window before showing it.
MyWindowObjectThatInheritsWindow window = new MyWindowObjectThatInheritsWindow();
var helper = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
var transformFromDevice = hwndSource.CompositionTarget.TransformFromDevice;
System.Windows.Point wpfMouseLocation = transformFromDevice.Transform(GetMousePositionWindowsForms());
window.Left = wpfMouseLocation.X - 300;
window.Top = wpfMouseLocation.Y - 240;
window.Show();
I am using the WriteableBitmapEx extension method to rotate a WriteableBitmap. bi in the code is a WritableBitmap. The RotateFree method rotates the bitmap in any degree and returns a new rotated WritableBitmap. My code:
private void rotate()
{
degree += 1;
var rotate = bi.RotateFree(degree);
ImageControl.Source = rotate;
}
My problem is since the ImageControl size is fixed, it causes the rotated bitmap to be clipped. So what is the best way to prevent this? I guess I am looking for a way to resize the ImageControl during rotation to prevent clipping. Any suggestions?
UPDATE
Based on this useful info Calculate rotated rectangle size from known bounding box coordinates I think I managed to calculate the bounding box width (bx) and height(by) and resize it accordingly during the rotation
double radian = (degree / 180.0) * Math.PI;
double bx = rotate.PixelWidth * Math.Cos(radian) + rotate.PixelHeight * Math.Sin(radian);
double by = rotate.PixelWidth * Math.Sin(radian) + rotate.PixelHeight * Math.Cos(radian);
While it appears that the ImageControl width and height increases/decreases during rotation, the image is still being clipped.
UPDATE 2
Based on #Rene suggestion, I managed to prevent the clipping. Combined with the ImageControl Width/Height calculation, the image size is retained during rotation by also setting its stretch property to NONE.
The issue now is to make sure the ImageControl resize from its center so that it does not appear moving. I can include a sample project if anyone interested
UPDATE 3
For those who might be interested the final solution. This is how I do it. The result is, the image is rotated without clipping and its size is retained during rotation. In addition, the rotation appears to originate from the center.
To adjust the ImageControl position as it's resizing so that the rotation appears to originated from center, I use this code.
var translationDelta = new Point((ImageControl.ActualWidth - bx) / 2.0, (ImageControl.ActualHeight - by) / 2.0);
UpdateImagePosition(translationDelta);
ApplyPosition();
// This code update the ImageControl position on the canvas
public void UpdateImagePosition(Point delta)
{
var newPosition = new Point(ImagePosition.X + delta.X, ImagePosition.Y + delta.Y);
ImagePosition = newPosition;
}
//This apply the new position to make the ImageControl rotate from center
public void ApplyPosition()
{
ObjComposite.TranslateX = ImagePosition.X;
ObjComposite.TranslateY = ImagePosition.Y;
}
Use RotateFree with the crop parameter set to false: RotateFree(degree, false). Also set the ImageControl Stretch property to Uniform: Stretch="Uniform".
rene
Can I get the Height and Width of an Image, if it has been Stretched by UniformToFill?
I tried Width and Height properties but they are always NaN.
If you want to know the dimensions of the image control, this is the way:
double theHeight = this.ActualHeight - img.Margin.Top - img.Margin.Bottom;
double theWidth = this.ActualWidth - img.Margin.Left - img.Margin.Right;
(img is the image control name in the code above, and in the codes below)
And if you want to know actual size of image (before it being stretched) you may try this:
BitmapSource SourceData = (BitmapSource)img.Source;
double imgWidth = SourceData.PixelWidth;
double imgHeight = SourceData.PixelHeight;
(I've Found this here)
Also this will get you the dimensions of image after resizing (But before uniforming):
double actWidth = img.ActualWidth;
double actHeight = img.ActualHeight;
So, one of those variables (actWidth or actHeight) must be equal to image control dimension, and the other will be higher than it.
Please note that the second and the third codes are not working if you call them in Window_Loaded event, since images are not loaded at that moment. You should use it after everything is loaded.
I'm working on some image processing and for debug I'm overlaying colours on the original bitmap.
The problem is the image is rendered in a picture box with SizeMode set to Zoom and invalidating every time I update a pixel is Really slow and just gets slower the larger picturebox is (for the same size image)
What I think might help is if I only invalidate the pixel(s) I've changed but I don't know how convert the co-ordinates of the pixel I've changed into a rectangle rendered on the control. Obviously if the image is being drawn larger than the original image then the rectangle I'm invalidating is going to be more than one pixel
Added a method to get the zoom and padding of the picture pox
private void CalculateZoomAndPadding()
{
Double imageAspect = (Double)pictureBox1.Image.Width / (Double)pictureBox1.Image.Height;
Double pbAspect = (Double)pictureBox1.Width / (Double)pictureBox1.Height;
Boolean heightRestricted = imageAspect < pbAspect;
hPadding = 0;
vPadding = 0;
if (heightRestricted)
{
zoom = (Double)pictureBox1.Height / (Double)pictureBox1.Image.Height;
Double imageWidth = (Double)pictureBox1.Image.Width * zoom;
hPadding = (Double)(pictureBox1.Width - imageWidth) / 2d;
}
else
{
zoom = (Double)pictureBox1.Width / (Double)pictureBox1.Image.Width;
Double imageHeight = (Double)pictureBox1.Image.Height * zoom;
vPadding = (Double)(pictureBox1.Height - imageHeight) / 2d;
}
}
then to invalidate a pixel called invalidate like this:
pictureBox1.Invalidate(new Rectangle(Convert.ToInt32(Math.Floor(x * zoom)) + Convert.ToInt32(hPadding) -1, Convert.ToInt32(Math.Floor(y * zoom)) + Convert.ToInt32(vPadding) -1, PixelSize, PixelSize));
when I first did this I only invalidated the are directly covered by the pixel but found that this was subject to rounding errors so expanded it to include a few extra.
Can you change all the pixels and then just invalidate the image once?
I'd just add a timer that fires 30 or 60 times per second that invalidates the whole control. While there might be a slight delay in updating you shouldn't be able to notice it due to your monitor's refresh rate most likely being 60 Hz only anyway.