Fading an Image - C# WPF - c#

I don't quite understand why it is so complicated as in a standard windows form the code below works just fine. But anyway.
I am trying to just fade an image in, and then fade it back out. At the moment I can't even get it to fade in, I feel pretty dumb because I'm sure there is something I am doing wrong. The for loop works but the image opacity does not change until it gets to 99 and then it suddenly changes. Please help because this is driving me mad.
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
for (int i = 1; i <+ 100; i++)
{
Logo.Opacity = i;
label1.Content = i;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 10);
dispatcherTimer.Start();
}
}
}

I don't know exactly what behaviour you want to get, but in WPF you should use animations. Probably you have to adapt the parameters:
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation da = new DoubleAnimation
{
From = 0,
To = 1,
Duration = new Duration(TimeSpan.FromSeconds(1)),
AutoReverse = true
};
Logo.BeginAnimation(OpacityProperty, da);
}

Opacity is double with 0.0 - 1.0 range. So the loop should be something like this.
for (double i = 0.0; i <= 1.0; i+=0.01)
{
Logo.Opacity = i;
label1.Content = i;
}
But as Clemens pointed out it also won't work. You're doing entire loop in one short burst. You should do one increment per timer tick:
double CurrentOpacity = 0.0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
CurrentOpacity += 0.01;
if(CurrentOpacity <= 1.0)
{
Logo.Opacity = CurrentOpacity;
label1.Content =CurrentOpacity;
}
else
{
dispatcherTimer.Stop();
}
}

Related

How to change the window position in wpf on a mouse click

I need to change the position of a window on mouse click.
here is the code.
private void Button_Click(object sender, RoutedEventArgs e)
{
for(int i=0; i<50; i++)
{
this.Top -= i;
this.Left -= i;
}
}
But whenever i run this program only the last position is shown. My intention is to move it continuosly till the end of loop.
Finally i found the answer myself. It s working perfectly as i expected. I used SynchronizationContext which can post Actions to update controls on UI thread.
public partial class Splash : Window
{
SynchronizationContext sc;
System.Timers.Timer t;
double i=0;
double tempTop;
double angle = 0;
public Splash()
{
InitializeComponent();
sc=SynchronizationContext.Current;
}
private void Move(object sender, MouseEventArgs e)
{
DragMove();
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void btnMinim_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
l1.Content = "Helicopter Moving";
if(t!=null)
{
t.Stop();
t.Dispose();
}
//for (double i = 0; i < 1; i += 0.05)
//{
// this.Top -= i;
// this.Left -= i;
// Thread.Sleep(100);
//}
//l1.Content = "Helicopter Stopped";
tempTop = this.Top;
t = new System.Timers.Timer();
t.Interval = 10;
t.Enabled = true;
t.Elapsed += Change;
t.Start();
}
void Change(object sender, EventArgs e)
{
if (i <= 3)
{
sc.Post(o =>
{
this.Top = tempTop * (Math.Cos(Math.PI * angle / 180));
this.Left -= i;
angle = (angle >= 360) ? 0 : ++angle;
i = i + 0.01;
}, null);
}
else
{
t.Stop();
i = i * -1;
}
}
}
}
Try this should work Thread.Sleep will not work for you as its a UI thread. You need timer to make this work
Timer t;
private void Button_Click(object sender, RoutedEventArgs e)
{
i=0;
if(t!=null)
{
t.Stop();
t.Dispose();
}
t = new Timer();
t.Interval = 800;
t.Enabled = true;
t.Tick += T_Tick;
t.Start();
}
int i=0;
private static void T_Tick(object sender, EventArgs e)
{
if(i<=50)
{
this.Top -= i;
this.Left -= i;
i++;
}
else
t.Stop();
}
Just start an animation when your click event triggers. You can define how long should the animation last.
Basic benefit of using animations instead of doing calculations manually is animations being run in separated thread, so you don't loose application's responsiveness.
What is more, you can edit your animations in separated tools, such as Blend without the need to verifying animations in runtime.
Few sources:
http://www.wpf-tutorial.com/styles/trigger-animations-enteractions-exitactions/
http://dotnetslackers.com/articles/wpf/IntroductionToWPFAnimations.aspx
http://www.wpftutorial.net/Animation.html

WPF use a timer to repeat an action

so I am new to WPF and am just trying to make a simple little program. When you hit a start button it will continuosly print fake code until you hit a stop button. I have tried to make it repeat until the stop button is hit 10 different ways but none of them are working. The TextBlock element will update once (or never) and then the whole program becomes unusable and the loading cursor comes up. I would guess that instead of going through a cycle, and then updating the TextBlocks, it is doing everything in the background and not updating visually.
public partial class MainWindow : Window
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
Random r1 = new Random();
bool stop = false;
int numUse
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
//Executes when the start button is hit, begins timer
private void Button_Click(object sender, RoutedEventArgs e)
{
do
{
dispatcherTimer.Tick += dispatcherTimer_Tick;
} while (stop == false);
}
//Executes when the stop button is hit, ends timers do while loop
private void Button_Click_1(object sender, RoutedEventArgs e)
{
stop = true;
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
numUse = r1.Next(1, 2);
if (numUse == 1)
{
CodeBlock1.Text = "struct group_info init_groups = { .usage = ATOMIC_INIT(2) }; ";
CodeBlock2.Text = "";
CodeBlock3.Text = "struct group_info *groups_alloc(int gidsetsize){ ";
CodeBlock4.Text = "struct group_info *group_info; ";
CodeBlock5.Text = "int nblocks; ";
CodeBlock6.Text = "int i; ";
CodeBlock7.Text = "";
CodeBlock8.Text = "initialize stream";
}
else if (numUse == 2)
{
CodeBlock1.Text = "if (gidsetsize <= NGROUPS_SMALL) ";
CodeBlock2.Text = "group_info->blocks[0] = group_info->small_block; ";
CodeBlock3.Text = " else { ";
CodeBlock4.Text = " for (i = 0; i < nblocks; i++) { ";
CodeBlock5.Text = "b = (void *)__get_free_page(GFP_USER); ";
CodeBlock6.Text = " goto out_undo_partial_alloc; ";
CodeBlock7.Text = "} ";
CodeBlock8.Text = "";
} else
{
}
}
}
}
I have tried for loops, do while, using different methods in different orders. I understand that I likely messed up while going those routes so any method is ok for my purposes. Obviously I am using a Timer in this case.
It is not necessary to repeatedly call dispatcherTimer.Tick += dispatcherTimer_Tick in the while loop of Button_Click. I suspect that while this loop is running, nothing else on the message pump will run, including ticks from the DispatcherTimer.
You could probably do away with stop and merely act on the DispatcherTimer directly by calling Stop() from anywhere in the code.
Perhaps this instead:
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Tick += dispatcherTimer_Tick; // set it up here
}
//Executes when the start button is hit, begins timer
private void Button_Click(object sender, RoutedEventArgs e)
{
dispatcherTimer.Start(); // start timer
}
//Executes when the stop button is hit, ends timers do while loop
private void Button_Click_1(object sender, RoutedEventArgs e)
{
dispatcherTimer.Stop(); // stop timer
}

Moving a picture box in timer C# Winforms

Ok so please keep answers very direct and i must say i am very new to C#, i don't know a lot of stuff. Without further adieu my problem.
I am trying to move a picture box horizontally across the screen on a timer.The timer must go infinitely. I have tried all i currently know in C# and searched around quite a lot but nothing answered my exact question which is what i need because of my lesser knowledge of C#. For the last two weeks i worked on graphics mostly and the rest of that was trying to get this to work, So i have no code in my game. This is because for anything to work i need this part to be working. My game is 2D topdown. Any and all help is appreciated.
Thank you for taking the time to read.
Edit
No more answers needed, Thank you Odrai for the answer, it helped me a lot.
Use pictureBox.Location = new Point(x, y) or set pictureBox.Left/Top/Right. You can define x and y as variabels and initialize them with a default value. Increment x on timer tick.
Sample 1:
public partial class Form1 : Form
{
private Random _random
public Form1()
{
InitializeComponent();
_random = new Random();
}
private void timer1_Tick(object sender, EventArgs e)
{
int x = _random.Next(0, 500);
int y = _random.Next(0, 500);
pictureBox1.Top += y;
pictureBox1.Left += x;
}
}
Sample 2:
private void timer1_Tick(object sender, EventArgs e)
{
this.SuspendLayout();
pictureBox.Location = new Point(picust.Location.X + 10, picust.Location.Y);
this.ResumeLayout();
}
Add two buttons with title LEFT and RIGHT to a form and write the following code.
It might give you an idea, how to do simple moving animations.
public partial class Form1 : Form
{
int difference = 0;
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
timer.Interval = 15;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
pictureBox1.Left += difference;
}
private void btnLeft_Click(object sender, EventArgs e)
{
difference = -2;
}
private void btnRight_Click(object sender, EventArgs e)
{
difference = 2;
}
}
Try This Code it will work :
private void timer1_Tick(object sender, EventArgs e)
{
int width = this.Width; // get the width of Form.
if(pictureBox1.Location.X > width - pictureBox1.Width) //to check condition if pic box is touch the boundroy of form width
{
pictureBox1.Location = new Point(1, pictureBox1.Location.Y); // pic box is set to the new point. here 1 is indicate of X coordinate.
}
else
{
pictureBox1.Location = new Point(pictureBox1.Location.X + 100, pictureBox1.Location.Y); // to move picture box from x coordinate by 100 Point.
}
}
//Try This //
picturebox1.Location = 0,0;

Simple Movement in C#

I want a label to move from the left of the form and stop at the center
I have been able to do this using
Timer tmr = new Timer();
int locx = 6;
public Form1()
{
InitializeComponent();
tmr.Interval = 2;
tmr.Tick += new EventHandler(tmr_Tick);
}
void tmr_Tick(object sender, EventArgs e)
{
label1.Location = new Point(locx, 33);
locx++;
if (locx == 215)
{
tmr.Stop();
}
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "QUICK SPARK";
tmr.Start();
}
I want to know if there is any better way to do this???...Any help will be appreciated
If you are using VS 2012 and C# 5, you can do this simply via await/async:
private async void Form1_Load(object sender, EventArgs e)
{
label1.Text = "QUICK SPARK";
for (int locx = 6; locx < 215; ++locx)
{
await Task.Delay(2);
label1.Location = new Point(locx, 33);
}
}
WinForm Animation Library [.Net3.5+]
A simple library for animating controls/values in .Net WinForm (.Net
3.5 and later). Key frame (Path) based and fully customizable.
https://falahati.github.io/WinFormAnimation/
new Animator2D(
new Path2D(new Float2D(-100, -100), c_control.Location.ToFloat2D(), 500))
.Play(c_control, Animator2D.KnownProperties.Location);
This moves the c_control control from -100, -100 to the location it was in first place in 500 ms.

C# - Make form semi-transparent while moving

Is there any way to make the form semi-transparent while it is being moved and then become opaque when it's not being moved anymore? I have tried the Form_Move event with no luck.
I'm stuck, any help?
The reason the form loads as semi-transparent is because the form has to be moved into the starting position, which triggers the Move event. You can overcome that by basing whether the opacity is set, on whether the form has fully loaded.
The ResizeEnd event fires after a form has finished moving, so something like this should work:
bool canMove = false;
private void Form1_Load(object sender, EventArgs e)
{
canMove = true;
}
private void Form1_Move(object sender, EventArgs e)
{
if (canMove)
{
this.Opacity = 0.5;
}
}
private void Form1_ResizeEnd(object sender, EventArgs e)
{
this.Opacity = 1;
}
To do it properly I expect you'd need to override the message processing to respond to the title bar being held, etc. But you could cheat, and just use a timer so that you make it opaque for a little while when moved, so continuous movement works:
[STAThread]
static void Main()
{
using (Form form = new Form())
using (Timer tmr = new Timer())
{
tmr.Interval = 500;
bool first = true;
tmr.Tick += delegate
{
tmr.Stop();
form.Opacity = 1;
};
form.Move += delegate
{
if (first) { first = false; return; }
tmr.Stop();
tmr.Start();
form.Opacity = 0.3;
};
Application.Run(form);
}
}
Obviously you could tweak this to fade in/out, etc - this is just to show the overall concept.

Categories