Move the zoomed image by gyroscope in xamarin - c#

I want to move the zoomed image with gyroscope. As you can see in below code I can do this thing by hand and I got a good result. I have to write something inside "Gyroscope_ReadingChanged" to convert gyroscope data to the Content.TranslationX and Content.TranslationY. Any help would be appreciated.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:video="clr-namespace:UbSports.Controls"
xmlns:local="clr-namespace:UbSports.Controls"
x:Class="UbSports.Pages.TestPage">
<local:PinchToZoomContainer VerticalOptions="FillAndExpand">
<local:PinchToZoomContainer.Content>
<Image x:Name="image" Source="waterfront.jpg" />
</local:PinchToZoomContainer.Content>
</local:PinchToZoomContainer>
</ContentPage>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestPage: ContentPage
{
public TestPage()
{
InitializeComponent();
}
}
public class PinchToZoomContainer : ContentView
{
public PinchToZoomContainer()
{
Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
try
{
Gyroscope.Start(SensorSpeed.UI);
}
catch (FeatureNotSupportedException fnsEx)
{
}
catch (Exception ex)
{
}
var panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += OnPanUpdated;
GestureRecognizers.Add(panGesture);
var pinchGesture = new PinchGestureRecognizer();
pinchGesture.PinchUpdated += OnPinchUpdated;
GestureRecognizers.Add(pinchGesture);
}
void Gyroscope_ReadingChanged(object sender, GyroscopeChangedEventArgs e)
{
var data = e.Reading;
if (data.AngularVelocity.X == 0 && data.AngularVelocity.Y == 0) return;
// do something
}
void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
startX = e.TotalX;
startY = e.TotalY;
Content.AnchorX = 0;
Content.AnchorY = 0;
break;
case GestureStatus.Running:
var maxTranslationX = Content.Scale * Content.Width - Content.Width;
Content.TranslationX = Math.Min(0, Math.Max(-maxTranslationX, xOffset + e.TotalX - startX));
var maxTranslationY = Content.Scale * Content.Height - Content.Height;
Content.TranslationY = Math.Min(0, Math.Max(-maxTranslationY, yOffset + e.TotalY - startY));
break;
case GestureStatus.Completed:
xOffset = Content.TranslationX;
yOffset = Content.TranslationY;
break;
}
}
void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
if (e.Status == GestureStatus.Started)
{
startScale = Content.Scale;
Content.AnchorX = 0;
Content.AnchorY = 0;
}
if (e.Status == GestureStatus.Running)
{
currentScale += (e.Scale - 1) * startScale;
currentScale = Math.Max(1, currentScale);
double renderedX = Content.X + xOffset;
double deltaX = renderedX / Width;
double deltaWidth = Width / (Content.Width * startScale);
double originX = (e.ScaleOrigin.X - deltaX) * deltaWidth;
double renderedY = Content.Y + yOffset;
double deltaY = renderedY / Height;
double deltaHeight = Height / (Content.Height * startScale);
double originY = (e.ScaleOrigin.Y - deltaY) * deltaHeight;
double targetX = xOffset - (originX * Content.Width) * (currentScale - startScale);
double targetY = yOffset - (originY * Content.Height) * (currentScale - startScale);
Content.TranslationX = targetX.Clamp(-Content.Width * (currentScale - 1), 0);
Content.TranslationY = targetY.Clamp(-Content.Height * (currentScale - 1), 0);
Content.Scale = currentScale;
}
if (e.Status == GestureStatus.Completed)
{
xOffset = Content.TranslationX;
yOffset = Content.TranslationY;
}
}
}

Related

Xamarin Forms PanGesture has inconsequent coordinates

I have a problem. I created an image within a AbsoluteLayout with a panGestureRecognizer, but when I use that to move the image in the app, it jumps back and forth. Very annoying. Here is the code I am using
private void AddImageToPreview(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
var image = (Image)e.NewItems[e.NewItems.Count - 1];
PanGestureRecognizer panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanUpdated;
image.GestureRecognizers.Add(panGesture);
MyLayout.Children.Add(image);
}
}
void PanUpdated(object sender, PanUpdatedEventArgs args)
{
Image image = (Image)sender;
if (args.StatusType.Equals(GestureStatus.Running))
{
x = args.TotalX;
y = args.TotalY;
image.TranslateTo(x, y, 1);
}
}
Can someone help me improve this, so this drag/drop system works smooth and fast!
I have a control purely made in Xamarin.Forms that you can use for the above mentioned usage:
using System;
using Xamarin.Forms;
using FFImageLoading.Forms;
public class ZoomImage : CachedImage
{
private const double MIN_SCALE = 1;
private const double MAX_SCALE = 4;
private const double OVERSHOOT = 0.15;
private double StartScale, LastScale;
private double StartX, StartY;
public ZoomImage()
{
var pinch = new PinchGestureRecognizer();
pinch.PinchUpdated += OnPinchUpdated;
GestureRecognizers.Add(pinch);
var pan = new PanGestureRecognizer();
pan.PanUpdated += OnPanUpdated;
GestureRecognizers.Add(pan);
var tap = new TapGestureRecognizer { NumberOfTapsRequired = 2 };
tap.Tapped += OnTapped;
GestureRecognizers.Add(tap);
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
}
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
return base.OnMeasure(widthConstraint, heightConstraint);
}
private void OnTapped(object sender, EventArgs e)
{
if (Scale > MIN_SCALE)
{
this.ScaleTo(MIN_SCALE, 250, Easing.CubicInOut);
this.TranslateTo(0, 0, 250, Easing.CubicInOut);
}
else
{
AnchorX = AnchorY = 0.5; //TODO tapped position
this.ScaleTo(MAX_SCALE, 250, Easing.CubicInOut);
}
}
private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
StartX = (1 - AnchorX) * Width;
StartY = (1 - AnchorY) * Height;
break;
case GestureStatus.Running:
AnchorX = Clamp(1 - (StartX + e.TotalX) / Width, 0, 1);
AnchorY = Clamp(1 - (StartY + e.TotalY) / Height, 0, 1);
break;
}
}
private void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
switch (e.Status)
{
case GestureStatus.Started:
LastScale = e.Scale;
StartScale = Scale;
AnchorX = e.ScaleOrigin.X;
AnchorY = e.ScaleOrigin.Y;
break;
case GestureStatus.Running:
if (e.Scale < 0 || Math.Abs(LastScale - e.Scale) > (LastScale * 1.3) - LastScale)
{ return; }
LastScale = e.Scale;
var current = Scale + (e.Scale - 1) * StartScale;
Scale = Clamp(current, MIN_SCALE * (1 - OVERSHOOT), MAX_SCALE * (1 + OVERSHOOT));
break;
case GestureStatus.Completed:
if (Scale > MAX_SCALE)
this.ScaleTo(MAX_SCALE, 250, Easing.SpringOut);
else if (Scale < MIN_SCALE)
this.ScaleTo(MIN_SCALE, 250, Easing.SpringOut);
break;
}
}
private T Clamp<T>(T value, T minimum, T maximum) where T: IComparable
{
if (value.CompareTo(minimum) < 0)
return minimum;
else if (value.CompareTo(maximum) > 0)
return maximum;
else
return value;
}
}
What this does:
Pinch zoom, Pan and Swipe movements together with double tap centre zoom and un-zoom
Note: I have used FFimageLoading's CachedImage because I needed to cache the data in case you do not intend this replace CachedImage with Xamarin.Forms.Image

How to do zooming and panning in image using xamarin cross platform

I want to zoom and pan an image in my app.But it is not working perfectly.
I tried this link: https://forums.xamarin.com/discussion/74168/full-screen-image-viewer-with-pinch-to-zoom-pan-to-move-tap-to-show-captions-for-xamarin-forms
Please help me..
Here is my XAML Code
<ContentPage.Content>
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" BackgroundColor="Yellow">
<Image Source="download" x:Name="img">
<Image.GestureRecognizers>
<PanGestureRecognizer PanUpdated="OnPanUpdated"/>
<PinchGestureRecognizer PinchUpdated="OnPinchUpdated"/>
<TapGestureRecognizer Tapped="OnTapped"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</ContentPage.Content>
My mainpage.cs
private const double MIN_SCALE = 1;
private const double MAX_SCALE = 4;
private const double OVERSHOOT = 0.15;
private double StartScale;
private double LastX, LastY;
private double StartX, StartY;
public MainPage()
{
InitializeComponent();
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
}
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
Scale = MIN_SCALE;
TranslationX = TranslationY = 0;
AnchorX = AnchorY = 0;
return base.OnMeasure(widthConstraint, heightConstraint);
}
private void OnTapped(object sender, EventArgs e)
{
if (Scale > MIN_SCALE)
{
this.ScaleTo(MIN_SCALE, 250, Easing.CubicInOut);
this.TranslateTo(0, 0, 250, Easing.CubicInOut);
}
else
{
AnchorX = AnchorY = 0.5; //TODO tapped position
this.ScaleTo(MAX_SCALE, 250, Easing.CubicInOut);
}
}
private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
if (Scale > MIN_SCALE)
switch (e.StatusType)
{
case GestureStatus.Started:
StartX = (1 - AnchorX) * Width;
StartY = (1 - AnchorY) * Height;
break;
case GestureStatus.Running:
TranslationX = Clamp(LastX + e.TotalX * Scale, -Width / 2, Width / 2);
TranslationY = Clamp(LastY + e.TotalY * Scale, -Height / 2, Height / 2);
break;
}
//switch (e.StatusType)
//{
// case GestureStatus.Started:
// StartX = (1 - AnchorX) * Width;
// StartY = (1 - AnchorY) * Height;
// break;
// case GestureStatus.Running:
// AnchorX = Clamp(1 - (StartX + e.TotalX) / Width, 0, 1);
// AnchorY = Clamp(1 - (StartY + e.TotalY) / Height, 0, 1);
// break;
//}
}
private void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
switch (e.Status)
{
case GestureStatus.Started:
StartScale = Scale;
AnchorX = e.ScaleOrigin.X;
AnchorY = e.ScaleOrigin.Y;
break;
case GestureStatus.Running:
double current = Scale + (e.Scale - 1) * StartScale;
Scale = Clamp(current, MIN_SCALE * (1 - OVERSHOOT), MAX_SCALE * (1 + OVERSHOOT));
break;
case GestureStatus.Completed:
if (Scale > MAX_SCALE)
this.ScaleTo(MAX_SCALE, 250, Easing.SpringOut);
else if (Scale < MIN_SCALE)
this.ScaleTo(MIN_SCALE, 250, Easing.SpringOut);
break;
}
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height); //must be called
img.TranslateTo(0, 0, 0, Easing.Linear);
}
private T Clamp<T>(T value, T minimum, T maximum) where T : IComparable
{
if (value.CompareTo(minimum) < 0)
return minimum;
else if (value.CompareTo(maximum) > 0)
return maximum;
else
return value;
}
}
When I zoom the image ,the image position look like this
Image gestures is not working perfectly.When double tap the image ,zoom in and zoom out work perfectly.

Moving Bitlines takes snapshot of background image with it in panel in C#

I am working on a project where I have to align series of images so for that I use lines created using bitmap. Now user can move and rotate this line in anywhere inside panel which has that image as background. Now I have already tried to make panel double buffered which solves the problem of background snapshot while rotating, but when I move that line it takes a piece of background with it. I also tried to refresh panel but that's not working.
Heres the code:
private bool _rotating;
private bool _dragging;
private int _clickX;
private int _clickY;
private Point _clickCoords;
private int _middleX;
private int _middleY;
private int _centerX;
private int _centerY;
private double _radius;
private DateTime lastRotate = DateTime.Today;
public void UpdateCircle(Line l)
{
_centerX = (l.EndPoint.X + l.StartPoint.X) / 2 + l.Left;
_centerY = (l.EndPoint.Y + l.StartPoint.Y) / 2 + l.Top;
_radius = GetDistance(l.StartPoint.X, l.StartPoint.Y, l.EndPoint.X, l.EndPoint.Y) / 2;
// panel5.Refresh();
}
public void UpdateMiddle(Line l)
{
_middleX = (l.EndPoint.X + l.StartPoint.X) / 2;
_middleY = (l.EndPoint.Y + l.StartPoint.Y) / 2;
// panel5.Refresh();
}
public double GetDistance(double x1, double y1, double x2, double y2)
{
return Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
public void LineMouseDown(object sender, MouseEventArgs e)
{
var l = (Line)sender;
if (GetDistance(e.X, e.Y, l.StartPoint.X, l.StartPoint.Y) < 30 ||
GetDistance(e.X, e.Y, l.EndPoint.X, l.EndPoint.Y) < 30)
{
_rotating = true;
}
else
{
_dragging = true;
panel5.Refresh();
}
_clickX = e.X;
_clickY = e.Y;
panel5.Refresh();
_clickCoords = new Point(l.Left + e.X, l.Top + e.Y);
UpdateCircle(l);
UpdateMiddle(l);
// panel5.Refresh();
}
public void LineMouseUp(object sender, MouseEventArgs e)
{
_rotating = false;
_dragging = false;
panel5.Refresh();
}
public void LineMouseMove(object sender, MouseEventArgs e)
{
// panel5.Refresh();
var l = (Line)sender;
if (_rotating)
{
if ((DateTime.Now - lastRotate).TotalMilliseconds > 60)
{
try
{
var angle = GetAngle(l.Left + e.X, l.Top + e.Y, _centerX, 0, _centerX, _centerY);
var newStartPoint = new Point(
(int)Math.Round(_middleX + _radius * Math.Sin(angle)),
(int)Math.Round(_middleY + _radius * Math.Cos(angle))
);
var newEndPoint = new Point(2 * _middleX - newStartPoint.X, 2 * _middleY - newStartPoint.Y);
l.SetPoints(newStartPoint, newEndPoint);
UpdateMiddle(l);
lastRotate = DateTime.Now;
}
catch
{
//ignored
}
}
}
else if (_dragging)
{
l.Left = l.Left + e.X - _clickX;
l.Top = l.Top + e.Y - _clickY;
// panel5.Refresh();
}
}
public double GetAngle(int x2, int y2, int x1, int y1, int x0, int y0)
{
double angle = Math.Atan2(y1 - y0, x1 - x0) - Math.Atan2(y2 - y0, x2 - x0);
return angle;
}
And heres how I create lines:
bitLine = new Line { LineColor = Color.Red, LineWidth = 2, StartPoint = new Point(x1, y1), EndPoint = new Point(x2, y2) };
bitLine2 = new Line { LineColor = Color.Red, LineWidth = 2, StartPoint = new Point(x1, y1), EndPoint = new Point(x2, y2) };
//bitLine.Cursor = Cursors.SizeAll;
bitLine.MouseDown += LineMouseDown;
bitLine.MouseUp += LineMouseUp;
bitLine.MouseMove += LineMouseMove;
bitLine2.MouseDown += LineMouseDown;
bitLine2.MouseUp += LineMouseUp;
bitLine2.MouseMove += LineMouseMove;
bitLine2.Click += bitLine2_Click;
bitLine.Click += bitLine_Click;
panel5.Controls.Add(bitLine);
panel5.Controls.Add(bitLine2);
pb.WireControl(bitLine);
pb.WireControl(bitLine2);
bitLine.Location = Program.line1_location;
bitLine2.Location = Program.line2_location;
So please any suggestions will be helpful. I am really stuck in this.
Here is screenshot of what is the problem

I can't drag while zoom in?

Into Copystransform, if I removed 2 in the end of line then I will could zoom in and out but could not drag while that have zoom in.
what else I did not remove then can't zoom and can't drag. It just zoom when the picture is small else if the picture is full screen then did not that.
Link:http://blogs.msdn.com/b/wsdevsol/archive/2014/06/10/constraining-manipulations.aspx
double mincale = 0.5;
//double maxscale = 10.0;
CompositeTransform savedtransform = new CompositeTransform();
private void Image_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
// FrameworkElement elemt = sender as FrameworkElement;
Image elemt = sender as Image;
CompositeTransform transform = elemt.RenderTransform as CompositeTransform;
//
copytransform(transform,savedtransform);
//apply
transform.ScaleX *= e.Delta.Scale;
transform.ScaleY *= e.Delta.Scale;
transform.TranslateX += e.Delta.Translation.X;
transform.TranslateY += e.Delta.Translation.Y;
if (transform.ScaleX < mincale) transform.ScaleX = mincale;
if (transform.ScaleY < mincale) transform.ScaleY = mincale;
// if (transform.ScaleX > maxscale) transform.ScaleX = maxscale;
// if (transform.ScaleY > maxscale) transform.ScaleY = maxscale;
if(elemt!=null)
{
if(!intersetElemnets(elemt,this.content,true))
{
copytransform(savedtransform, transform);
}
}
/*
double scalewidth = Zoomimages.ActualWidth * ct.ScaleX;
double scleheight = Zoomimages.ActualHeight * ct.ScaleY;
double xdiff = Math.Max(0, (scalewidth - this.content.ActualWidth) / 2);
double ydiff = Math.Max(0, (scleheight - this.content.ActualHeight) / 2);
if (Math.Abs(ct.TranslateX) > xdiff)
ct.TranslateX = xdiff * Math.Sign(e.Delta.Translation.X);
if (Math.Abs(ct.TranslateY) > ydiff)
ct.TranslateY = ydiff * Math.Sign(e.Delta.Translation.Y);
* */
}
private bool intersetElemnets(FrameworkElement inner, FrameworkElement outer,bool contains)
{
GeneralTransform testTransform = inner.TransformToVisual(outer);
//
Rect boundsinner = new Rect(0,0,inner.ActualWidth,inner.ActualHeight);
Rect bboxouter = new Rect(0, 0, outer.ActualWidth, outer.ActualHeight);
Rect bboxinner = testTransform.TransformBounds(boundsinner);
if(contains)
{
return bboxinner.X > bboxouter.Y &&
bboxinner.Y > bboxouter.Y &&
bboxinner.Right < bboxouter.Right &&
bboxinner.Bottom < bboxouter.Bottom;
}
else
{
bboxouter.Intersect(bboxinner);
return !bboxouter.IsEmpty;
}
}
private void copytransform(CompositeTransform orig,CompositeTransform copy)
{
copy.TranslateX = orig.TranslateX;
copy.TranslateY = orig.TranslateY;
copy.ScaleX = orig.ScaleX;
copy.ScaleY = orig.ScaleY;
}

Tool strip menu items not displaying

When my windows form loads the tool strip menu item bar is there but the items inside it are not shown until I hover over them or press alt.
Also, my colordialog box wont open until after I click the change color icon in my menu and then press Alt.
I've had a look through the properties to make sure there is no hide property on or something but I can't seem to find anything.
I've posted some links below to show you what's happening.
When it opens up: http://gyazo.com/c1f4fa4d27e3f54a65b1f8a3da6cd0da
When I press alt or hover over menu: http://gyazo.com/c86c5dfb723647c025f89a0c14da6766
Not sure what code to put in.
Changing color bit:
private void changeColourToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = colorDialog1.ShowDialog();
}
I just dragged the elements on from the toolbox.
All Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
init();
start();
this.DoubleBuffered = true;
}
//code to convert HSB to RGB from HSB.cs. All your code so i made it take up less space.
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b) { this.a = 0xff; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public HSBColor(int a, float h, float s, float b) { this.a = a; this.h = Math.Min(Math.Max(h, 0), 255); this.s = Math.Min(Math.Max(s, 0), 255); this.b = Math.Min(Math.Max(b, 0), 255); }
public float H { get { return h; } }
public float S { get { return s; } }
public float B { get { return b; } }
public int A { get { return a; } }
public Color Color { get { return FromHSB(this); } }
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b; float dif = hsbColor.b * hsbColor.s / 255f; float min = hsbColor.b - dif; float h = hsbColor.h * 360f / 255f;
if (h < 60f) { r = max; g = h * dif / 60f + min; b = min; }
else if (h < 120f) { r = -(h - 120f) * dif / 60f + min; g = max; b = min; }
else if (h < 180f) { r = min; g = max; b = (h - 120f) * dif / 60f + min; }
else if (h < 240f) { r = min; g = -(h - 240f) * dif / 60f + min; b = max; }
else if (h < 300f) { r = (h - 240f) * dif / 60f + min; g = min; b = max; }
else if (h <= 360f) { r = max; g = min; b = -(h - 360f) * dif / 60 + min; }
else { r = 0; g = 0; b = 0; }
}
return Color.FromArgb(hsbColor.a, (int)Math.Round(Math.Min(Math.Max(r, 0), 255)), (int)Math.Round(Math.Min(Math.Max(g, 0), 255)), (int)Math.Round(Math.Min(Math.Max(b, 0), 255)));
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static float xy;
private int c = 0;
//private Image picture; Taken out, not needed
// create rectangle variable JGB
Rectangle rec;
private Graphics g1;
//private Cursor c1, c2; Taken out, not needed
private System.Drawing.Bitmap bitmap;
public void init()
{
//setSize(640, 480); changed this code to JGB:
this.Size = new Size(640, 480);
// Taken all lines out below. Not needed.
/*finished = false;
addMouseListener(this);
addMouseMotionListener(this);
c1 = new Cursor(Cursor.WAIT_CURSOR);
c2 = new Cursor(Cursor.CROSSHAIR_CURSOR); */
x1 = 640;
y1 = 480;
xy = (float)x1 / (float)y1;
//picture = createImage(x1, y1); Taken out and replaced with JGB:
bitmap = new Bitmap(x1, y1);
//g1 = picture.getGraphics(); changed to get my bitmap
g1 = Graphics.FromImage(bitmap);
//finished = true; Finished variable deleted so not needed
}
//Code below didnt appear to do anything so i deleted it
/*public void destroy() // delete all instances
{
if (finished)
{
removeMouseListener(this);
removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
System.gc(); // garbage collection
}
} */
public void start()
{
//action = false;
//rectangle = false;
initvalues();
// added dialog box for instance loading and save varaibles needed for position and zoom to text file
DialogResult dialog = MessageBox.Show("Would You Like to Load Your Last Instance?", "Load Instance?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dialog == DialogResult.Yes)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\Writelines.txt");
xzoom = System.Convert.ToDouble(lines[0]);
yzoom = System.Convert.ToDouble(lines[1]);
xstart = System.Convert.ToDouble(lines[2]);
ystart = System.Convert.ToDouble(lines[3]);
}
else
{
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
}
mandelbrot();
}
public void stop()
{
}
/*public void paint(Graphics g, PaintEventArgs e)
{
update(g);
}
public void update(Graphics g)
{
//g.DrawImage(picture, 0, 0);
}*/
private void mandelbrot()
{
int x, y;
float h, b, alt = 0.0f;
Color color;
Pen pen = new Pen(Color.Black);
for (x = 0; x < x1; x += 2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y, c);
if (h != alt)
{
b = 1.0f - h * h;
color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255));
pen = new Pen(color);
alt = h;
}
g1.DrawLine(pen, x, y, x + 1, y);
}
}
private float pointcolour(double xwert, double ywert, int j)
{
double r = 0.0, i = 0.0, m = 0.0;
// int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues()
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy)
xstart = xende - (yende - ystart) * (double)xy;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
g1.DrawImage(bitmap, 0, 0, x1, y1);
using (Pen pen = new Pen(Color.White, 2))
{
e.Graphics.DrawRectangle(pen, rec);
}
Invalidate();
}
//added load method
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
xe = e.X;
ye = e.Y;
if (xs < xe)
{
if (ys < ye) rec = new Rectangle(xs, ys, (xe - xs), (ye - ys));
else rec = new Rectangle(xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) rec = new Rectangle(xe, ys, (xs - xe), (ye - ys));
else rec = new Rectangle(xe, ye, (xs - xe), (ys - ye));
}
this.Invalidate();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// e.consume();
xs = e.X;
ys = e.Y; // starting point y
this.Invalidate();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
rec = new Rectangle(0, 0, 0, 0);
if (e.Button == MouseButtons.Left)
{
int z, w;
//e.consume();
//xe = e.X;
//ye = e.Y;
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
string stringxzoom = xzoom.ToString();
string stringyzoom = yzoom.ToString();
string stringystart = ystart.ToString();
string stringxstart = xstart.ToString();
string[] lines = { stringxzoom, stringyzoom, stringxstart, stringystart };
System.IO.File.WriteAllLines(#"C:\Users\Public\Writelines.txt", lines);
this.Invalidate();
//Repaint();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
dialog.InitialDirectory =System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
dialog.Title = "Save Image";
dialog.FileName = "";
dialog.Filter = "JPEG|*.jpg";
dialog.ShowDialog();
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void changeColourToolStripMenuItem_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
}
private void menuToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
}
Ok so after hours of trying to figure this out i found the solution. A random invalidate was messing it up.
Thanks anyway to #Sjips for the fast help.

Categories