What I need is to set the Position property on WPF's MediaElement control. But when I play the video, (either via Play() or through some kind of animation on Opacity) it is is not working at all. It is showing 00:00:00 time, but I would expect it to be set to 00:00:05.
I have hard-coded Position value and it is not working at all.
Just In case I am going to put all my code I have so u can see the whole animation logic.
Any clue?
public partial class CrossFadeTransition : UserControl
{
DoubleAnimation _doubleAnimationFrontPlayer = new DoubleAnimation();
DoubleAnimation _doubleAnimationBackPlayer = new DoubleAnimation();
Storyboard _sb1 = new Storyboard();
Storyboard _sb2 = new Storyboard();
public TimeSpan Duration = TimeSpan.FromSeconds(2);
public Dictionary<string, Position2D> PlayerPosition { set; get; }
public CrossFadeTransition()
{
InitializeComponent();
Player1.LoadedBehavior = MediaState.Manual;
Player1.UnloadedBehavior = MediaState.Stop;
Player2.LoadedBehavior = MediaState.Manual;
Player2.UnloadedBehavior = MediaState.Stop;
PlayerPosition = new Dictionary<string, Position2D>();
PlayerPosition.Add("Player1", Position2D.Front);
PlayerPosition.Add("Player2", Position2D.Back);
}
Position2D positionPlayer1;
Position2D positionPlayer2;
public void Stop()
{
if (Player1.IsEnabled)
Player1.Stop();
if (Player2.IsEnabled)
Player2.Stop();
}
public void Start(Uri uri, int? position)
{
try
{
positionPlayer1 = PlayerPosition["Player1"];
positionPlayer2 = PlayerPosition["Player2"];
if (positionPlayer1 == Library.Position2D.Back)
{
Player1.Source = uri;
if (Player1.IsEnabled)
Player1.Stop();
Player1.Position = TimeSpan.FromSeconds(5); // IT IS NOT WORKING !!!
Player1.Play();
}
if (positionPlayer2 == Library.Position2D.Back)
{
Player2.Source = uri;
if (Player2.IsEnabled)
Player2.Stop();
Player2.Position = TimeSpan.FromSeconds(5); // IT IS NOT WORKING !!!
Player2.Play();
}
_sb1.Children.Clear();
_sb2.Children.Clear();
if (positionPlayer1 == Position2D.Front)
{
_doubleAnimationFrontPlayer.From = 1;
_doubleAnimationFrontPlayer.To = 0;
_doubleAnimationFrontPlayer.Duration = new Duration(Duration);
PlayerPosition["Player1"] = Position2D.Back;
}
else if (positionPlayer1 == Position2D.Back)
{
_doubleAnimationFrontPlayer.From = 0;
_doubleAnimationFrontPlayer.To = 1;
_doubleAnimationFrontPlayer.Duration = new Duration(Duration);
PlayerPosition["Player1"] = Position2D.Front;
}
if (positionPlayer2 == Position2D.Front)
{
_doubleAnimationBackPlayer.From = 1;
_doubleAnimationBackPlayer.To = 0;
_doubleAnimationBackPlayer.Duration = new Duration(Duration);
PlayerPosition["Player2"] = Position2D.Back;
}
else if (positionPlayer2 == Position2D.Back)
{
_doubleAnimationBackPlayer.From = 0;
_doubleAnimationBackPlayer.To = 1;
_doubleAnimationBackPlayer.Duration = new Duration(Duration);
PlayerPosition["Player2"] = Position2D.Front;
}
_sb1.Children.Add(_doubleAnimationFrontPlayer);
Storyboard.SetTargetProperty(_doubleAnimationFrontPlayer, new PropertyPath("(Panel.Opacity)"));
Storyboard.SetTarget(_doubleAnimationFrontPlayer, Player1);
_sb1.Completed += _sb1_Completed;
_sb1.Begin();
//
_sb2.Children.Add(_doubleAnimationBackPlayer);
Storyboard.SetTargetProperty(_doubleAnimationBackPlayer, new PropertyPath("(Panel.Opacity)"));
Storyboard.SetTarget(_doubleAnimationBackPlayer, Player2);
_sb2.Completed += _sb2_Completed;
_sb2.Begin();
}
catch (Exception)
{
throw;
}
}
void _sb2_Completed(object sender, EventArgs e)
{
_sb2.Completed -= _sb2_Completed;
Debug.WriteLine("Player2 COMPLETED " + DateTime.Now.TimeOfDay);
if (positionPlayer2 == Position2D.Front)
{
Player2.Stop();
}
}
void _sb1_Completed(object sender, EventArgs e)
{
_sb1.Completed -= _sb1_Completed;
Debug.WriteLine("Player1 COMPLETED " + DateTime.Now.TimeOfDay);
if (positionPlayer1 == Position2D.Front)
{
Player1.Stop();
}
}
}
I have tried to do like
Player2.Play();
Player2.Pause();
Player2.Position = TimeSpan.FromSeconds(5); // IT IS NOT WORKING !!!
Player2.Play();
But no joy...
I found some solution. It is not completely ideal because sometimes it shows the first video frame, but at least it is working.
We need those events where we can apply new Position.
void Player2_MediaOpened(object sender, RoutedEventArgs e)
{
Player2.Position = new TimeSpan(0, 0, 7);
}
void Player1_MediaOpened(object sender, RoutedEventArgs e)
{
Player1.Position = new TimeSpan(0, 0, 7);
}
We have to close Mediaelement like this.
Player1.Stop();
Player1.Close();
Player1.Source = uri;
Player1.Play();
Have fun! (beer)
Related
I have a list of images(Helper.theaterImagesInfo) that i am reading through a foreach loop and continuing infinite loop using while until a form closed. images display well with the code below
Application.DoEvents();
await Task.Delay(img.durationInMilliseconds);//img.durationInMilliseconds
this.PictureBox1.Image = img.ImageHere;
Now i want to implement fade effect to those images displaying. Each image is displayed after 5 seconds.
Function to apply fade:
private int intCount = 0;
private List<Bitmap> lstFade = new List<Bitmap>();
private void ApplyFade(Bitmap imgTarget, Bitmap imgSource)
{
int intX = 0;
int intY = 0;
int intAmount = 10;
Rectangle rctDest = new Rectangle(intX, intY,
imgTarget.Width, imgTarget.Height);
using (var tmpBitMap = new Bitmap(imgSource))
using (var gTemp = Graphics.FromImage(tmpBitMap))
for (int i = 0; i <= intAmount; i++)
{
gTemp.DrawImage(imgSource, intX, intY);
ColorMatrix cmColors = new ColorMatrix();
cmColors.Matrix33 = System.Convert.ToSingle(i /
(double)intAmount);
ImageAttributes iaAttributes = new ImageAttributes();
iaAttributes.SetColorMatrix(cmColors);
gTemp.DrawImage(imgTarget, rctDest, intX, intY,
imgTarget.Width, imgTarget.Height, GraphicsUnit.Pixel,
iaAttributes);
lstFade.Add((Bitmap)tmpBitMap.Clone());
}
}
Timer:
private void timer1_Tick(object sender, EventArgs e)
{
intCount += 2;
if (intCount > 10)
{
timer1.Stop();
}
else
{
PictureBox1.Image = lstFade[intCount];
}
}
and here reading list and applying fade to images
public int x=1;
private async void TheaterForm_Shown(object sender, EventArgs e)
{
if (this.PictureBox1.Image == null) SetDefaultImage();
if (Helper.theaterImagesInfo != null && Helper.theaterImagesInfo.Count >
0)
{
while (x == 1)
{
foreach (var img in Helper.theaterImagesInfo.ToList())
{
if (img.IsAnimated)
{
try
{
Application.DoEvents();
var imgS = new Bitmap(this.PictureBox1.Image);
await Task.Delay(img.durationInMilliseconds);
var imgT = new Bitmap(img.ImageHere);
ApplyFade(imgT, imgS);
intCount = 0;
timer1.Interval = 200;
timer1.Start();
}
catch { }
}
else
{
try
{
Application.DoEvents();
await Task.Delay(img.durationInMilliseconds);
var imgS = new Bitmap(this.PictureBox1.Image);
var imgT = new Bitmap(img.ImageHere);
ApplyFade(imgT, imgS);
intCount = 0;
timer1.Interval = 200;
timer1.Start();
}
catch { }
}
if (this.x == 0)
{
break; // exit the for loop early
}
}
}
SetDefaultImage();
}
}
Problem
Fade is applied between starting two images and then keep on the same fading process with those two images. Seems like ApplyFade function doesn't apply again the imgSource and imgTarget once passed through the parameter
I have a timer, how starts, when the text in a label appears and stop when you click on a button. Now i want to stop the reaktiontime and save it in a list, which i want to sort, so i can give out the fastest and lowest reaktiontime in a label. but in my code every time it shows 00:00:00 in the messagebox :(
public partial class Form1 : Form
{
Random r = new Random();
Random Farbe = new Random();
bool Start_MouseClick;
IList<string> Reaktionszeitliste = new List<string>() {};
IList<Color> myColors = new[] { Color.Red, Color.Blue, Color.Green, Color.White, Color.Yellow };
string[] colors = { "Rot", "Blau", "Grün", "Gelb", "Weiß" };
int Timeleft = 5;
int summe = 0, z;
string Reaktionszeit;
int Zeit;
int Spielzuege = 0;
DateTime Time1;
DateTime Time2;
TimeSpan ts;
private void btnRot_Click(object sender, EventArgs e)
{
Spielzuege = Spielzuege + 1;
timMessung.Stop();
if (Start_MouseClick == true)
{
int summe = 0, z;
lblAnzeige.Text = " ";
while (summe <= 0)
{
z = r.Next(1, 6);
summe = summe + z;
}
lblAnzeige.Text += colors[summe - 1] + "\n";
Zeit = 0;
timMessung.Enabled = true;
if (ckbExtrem.Checked == false)
{
lblAnzeige.ForeColor = myColors[Farbe.Next(myColors.Count)];
}
else
{
lblAnzeige.ForeColor = Color.FromArgb(Farbe.Next(256), Farbe.Next(256), Farbe.Next(256));
}
if (Spielzuege == 15)
{
if (txbPlayer2.Text != "")
{
MessageBox.Show("Spieler 2: Machen Sie sich bereit!");
}
else
{
MessageBox.Show(Convert.ToString(ts));
}
}
}
}
private void txbStart_MouseClick(object sender, MouseEventArgs e)
{
if (txbPlayer1.Text == "" && txbPlayer2.Text == "")
{
MessageBox.Show("Bitte geben Sie Spielername(n) ein!");
}
else
{
timVerzögerung.Enabled = true;
panel1.Visible = false;
lblAnzeige.Text = " ";
txbStart.Visible = false;
textBox1.Visible = false;
Start_MouseClick = true;
while (summe <= 0)
{
z = r.Next(1, 6);
summe = summe + z;
}
}
}
private void timMessung_Tick(object sender, EventArgs e)
{
if (timMessung.Enabled == true)
{
Time1 = DateTime.Now;
}
else
{
Time2 = DateTime.Now;
ts = Time1 - Time2;
int differenceInMilli = ts.Milliseconds;
}
}
In a first run i tried to alter your code so that it should run. But i found so many (coding style) issues within there that i simply wrote a completely new example. It also has some minor issues (e.g. size of buttons; it is possible that a color button occurs twice). But it hopefully shows you how TimeSpan and all the other parts can work together.
The Form1.cs file:
public partial class Form1 : Form
{
private Random _Random;
private List<TimeSpan> _ReactionTimes;
private Stopwatch _Stopwatch;
public Form1()
{
InitializeComponent();
_Stopwatch = new Stopwatch();
_Random = new Random(42);
_ReactionTimes = new List<TimeSpan>();
}
private Button CreateButton(Color color)
{
var button = new Button();
button.Click += OnColorButtonClick;
button.BackColor = color;
button.Text = color.Name;
return button;
}
private Button GetRandomButton()
{
var randomIndex = _Random.Next(0, flowLayoutPanel.Controls.Count);
return (Button)flowLayoutPanel.Controls[randomIndex];
}
private Color GetRandomColor()
{
var randomKnownColor = (KnownColor)_Random.Next((int)KnownColor.AliceBlue, (int)KnownColor.ButtonFace);
return Color.FromKnownColor(randomKnownColor);
}
private void InitializeColorButtons(int numberOfColors)
{
var buttons = Enumerable.Range(1, numberOfColors)
.Select(index => GetRandomColor())
.Select(color => CreateButton(color));
foreach (var button in buttons)
{
flowLayoutPanel.Controls.Add(button);
}
}
private void OnButtonStartClick(object sender, EventArgs e)
{
InitializeColorButtons((int)numericUpDownColors.Value);
StartMeasurement();
}
private void OnColorButtonClick(object sender, EventArgs e)
{
var button = (Button)sender;
if (button.Text != labelColorToClick.Text)
{
errorProviderWrongButton.SetIconPadding(button, -20);
errorProviderWrongButton.SetError(button, "Sorry, wrong button.");
return;
}
StopMeasurement();
_ReactionTimes.Add(_Stopwatch.Elapsed);
UpdateSummary();
}
private void StartMeasurement()
{
buttonStart.Enabled = false;
numericUpDownColors.Enabled = false;
labelColorToClick.Text = GetRandomButton().Text;
_Stopwatch.Reset();
_Stopwatch.Start();
}
private void StopMeasurement()
{
_Stopwatch.Stop();
errorProviderWrongButton.Clear();
flowLayoutPanel.Controls.Clear();
numericUpDownColors.Enabled = true;
buttonStart.Enabled = true;
labelColorToClick.Text = String.Empty;
}
private void UpdateSummary()
{
labelSummary.Text = String.Format("Current: {0:0.000} Minimum: {1:0.000} Maximum: {2:0.000}", _ReactionTimes.Last().TotalSeconds, _ReactionTimes.Min().TotalSeconds, _ReactionTimes.Max().TotalSeconds);
}
}
The Form1.Designer.cs file:
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.flowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel();
this.labelColorToClick = new System.Windows.Forms.Label();
this.buttonStart = new System.Windows.Forms.Button();
this.labelSummaryHeader = new System.Windows.Forms.Label();
this.labelSummary = new System.Windows.Forms.Label();
this.errorProviderWrongButton = new System.Windows.Forms.ErrorProvider(this.components);
this.numericUpDownColors = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.errorProviderWrongButton)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownColors)).BeginInit();
this.SuspendLayout();
//
// flowLayoutPanel
//
this.flowLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.flowLayoutPanel.Location = new System.Drawing.Point(12, 41);
this.flowLayoutPanel.Name = "flowLayoutPanel";
this.flowLayoutPanel.Size = new System.Drawing.Size(560, 386);
this.flowLayoutPanel.TabIndex = 0;
//
// labelColorToClick
//
this.labelColorToClick.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelColorToClick.Location = new System.Drawing.Point(174, 12);
this.labelColorToClick.Name = "labelColorToClick";
this.labelColorToClick.Size = new System.Drawing.Size(398, 23);
this.labelColorToClick.TabIndex = 1;
this.labelColorToClick.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(93, 12);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(75, 23);
this.buttonStart.TabIndex = 2;
this.buttonStart.Text = "Start";
this.buttonStart.UseVisualStyleBackColor = true;
this.buttonStart.Click += new System.EventHandler(this.OnButtonStartClick);
//
// labelSummaryHeader
//
this.labelSummaryHeader.Location = new System.Drawing.Point(12, 430);
this.labelSummaryHeader.Name = "labelSummaryHeader";
this.labelSummaryHeader.Size = new System.Drawing.Size(75, 23);
this.labelSummaryHeader.TabIndex = 3;
this.labelSummaryHeader.Text = "Summary:";
this.labelSummaryHeader.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelSummary
//
this.labelSummary.Location = new System.Drawing.Point(93, 430);
this.labelSummary.Name = "labelSummary";
this.labelSummary.Size = new System.Drawing.Size(479, 23);
this.labelSummary.TabIndex = 4;
this.labelSummary.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// errorProviderWrongButton
//
this.errorProviderWrongButton.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
this.errorProviderWrongButton.ContainerControl = this;
//
// numericUpDownColors
//
this.numericUpDownColors.Location = new System.Drawing.Point(12, 14);
this.numericUpDownColors.Minimum = new decimal(new int[] {
2,
0,
0,
0});
this.numericUpDownColors.Name = "numericUpDownColors";
this.numericUpDownColors.Size = new System.Drawing.Size(75, 20);
this.numericUpDownColors.TabIndex = 5;
this.numericUpDownColors.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// Form1
//
this.ClientSize = new System.Drawing.Size(584, 462);
this.Controls.Add(this.numericUpDownColors);
this.Controls.Add(this.labelSummary);
this.Controls.Add(this.labelSummaryHeader);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.labelColorToClick);
this.Controls.Add(this.flowLayoutPanel);
this.Name = "Form1";
((System.ComponentModel.ISupportInitialize)(this.errorProviderWrongButton)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownColors)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel;
private System.Windows.Forms.Label labelColorToClick;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Label labelSummaryHeader;
private System.Windows.Forms.Label labelSummary;
private System.Windows.Forms.ErrorProvider errorProviderWrongButton;
private System.Windows.Forms.NumericUpDown numericUpDownColors;
}
I think your problem here is that the resolution of DateTime is less than the intervals that you are trying to measure.
Instead of using DateTime, try the following:
Create a private Stopwatch field called stopwatch.
Stopwatch stopwatch = new Stopwatch();
Then change your tick handler to:
private void timMessung_Tick(object sender, EventArgs e)
{
if (timMessung.Enabled == true)
{
stopwatch.Restart();
}
else
{
ts.stopwatch.Elapsed();
}
}
However, I'm also not sure about your logic to do with when you restart the stopwatch. (Where I put stopwatch.Restart().) Do you really want to keep restarting the stopwatch at that point?
use:
ts = Time1.subtract(Time2);
How to calculate datetime diffrence:
How to calculate hours between 2 different dates in c#
I am creating dynamic text fields and storing Position and font etc details in an Arraylist. So for example if I click 3 times on Form I am generating 3 random numbers and showing it on clicked position on form. I have one selector button when it is clicked then adding more text functionality is disabled.
Now after when selector button is clicked and if I click ( MouseDown event) on any text then it should move along mouse until MouseUp event is not fired and place on new drop position.
After hours of struggling and searching I found This Solution, So I saved the position and checked with IsPointOnLine method but still its not draggable.
Thank you for any help.
Update: managed to get foreach on place but its still not dragging the selected element.
Form1.Class
public partial class Form1 : Form
{
private Point mouseDownPosition = new Point(0, 0);
private Point mouseMovePosition = new Point(0, 0);
private int mousePressdDown;
IList drawnItemsList = new List<DrawingData>();
private bool dragging;
private bool isSelectorClicked; // if selector button is clicked
DrawingData draggingText;
Random rnd;
int clicked = 0;
public Form1()
{
InitializeComponent();
this.rnd = new Random();
this.isSelectorClicked = false;
dragging = false;
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mouseMovePosition = e.Location;
if (e.Button == MouseButtons.Left)
mousePressdDown = 1;
if (isSelectorClicked)
{
foreach (DrawingData a in drawnItemsList)
{
if (a.IsPointOnLine(e.Location, 5))
{
draggingText = a;
dragging = true;
}
}
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDownPosition = e.Location;
if (dragging)
{
draggingText.cur = mouseDownPosition;
this.Invalidate();
}
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (mousePressdDown == 1 && isSelectorClicked == false)
{
label1.Text = "X: " + mouseMovePosition.X.ToString();
label2.Text = "Y: " + mouseMovePosition.Y.ToString();
this.Invalidate();
DrawingData a = new DrawingData(mouseMovePosition, mouseDownPosition, rnd.Next().ToString(), FontStyle.Bold, 30, "Candara", Brushes.Blue);
drawnItemsList.Add(a);
this.clicked++;
}
mousePressdDown = 0;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if(drawnItemsList.Count != 0)
{
foreach (DrawingData a in drawnItemsList)
{
draw(e.Graphics, a);
}
if (mousePressdDown != 0)
{
draw(e.Graphics, mouseDownPosition, mouseMovePosition, FontStyle.Bold, 30, "Candara", Brushes.Blue);
}
}
}
private void draw(Graphics e, Point mold, Point mcur, FontStyle fontWeight, int fontSize, string fontName, Brush fontColor)
{
Pen p = new Pen(Color.Black, 2);
using (Font useFont = new Font(fontName, fontSize, fontWeight))
{
string header2 = rnd.Next().ToString();
RectangleF header2Rect = new RectangleF();
int moldX = mold.X - 5;
int moldY = mold.Y;
header2Rect.Location = new Point(moldX, moldY);
header2Rect.Size = new Size(600, ((int)e.MeasureString(header2, useFont, 600, StringFormat.GenericTypographic).Height));
e.DrawString(header2, useFont, fontColor, header2Rect);
}
}
private void draw(Graphics e, DrawingData a)
{
Pen p = new Pen(Color.Black, 2);
using (Font useFont = new Font(a.FontName, a.FontSize, a.FontWeight))
{
string header2 = rnd.Next().ToString();
RectangleF header2Rect = new RectangleF();
int moldX = a.old.X - 5;
int moldY = a.old.Y;
header2Rect.Location = new Point(moldX, moldY);
header2Rect.Size = new Size(600, ((int)e.MeasureString(header2, useFont, 600, StringFormat.GenericTypographic).Height));
e.DrawString(a.Rand, useFont, a.FontColor, header2Rect);
}
}
private void Select_button_Click(object sender, EventArgs e)
{
this.isSelectorClicked = true;
}
private void WriteNewText_button_Click(object sender, EventArgs e)
{
this.isSelectorClicked = false;
}
}
DrawingData.Class
[Serializable]
public class DrawingData
{
private Point Start; // mouseDown position
private Point End; // mouseUp poslition
private string randValue; // random data value
private FontStyle fontWeight;
private int fontSize;
private string fontName;
private Brush fontColor;
public DrawingData()
{
Start = new Point(0, 0);
End = new Point(0, 0);
randValue = String.Empty;
fontWeight = FontStyle.Bold;
}
public DrawingData(Point old, Point cur, string rand, FontStyle fs, int fSize, string fName, Brush fColor)
{
Start = old;
End = cur;
randValue = rand;
fontWeight = fs;
fontSize = fSize;
fontName = fName;
fontColor = fColor;
}
public float slope
{
get
{
return (((float)End.Y - (float)Start.Y) / ((float)End.X - (float)Start.X));
}
}
public float YIntercept
{
get
{
return Start.Y - slope * Start.X;
}
}
public bool IsPointOnLine(Point p, int cushion)
{
float temp = (slope * p.X + YIntercept);
if (temp >= (p.Y - cushion) && temp <= (p.Y + cushion))
{
return true;
}
else
{
return false;
}
}
public FontStyle FontWeight
{
get
{
return fontWeight;
}
set
{
fontWeight = value;
}
}
public int FontSize
{
get
{
return fontSize;
}
set
{
fontSize = value;
}
}
public string FontName
{
get
{
return fontName;
}
set
{
fontName = value;
}
}
public Brush FontColor
{
get
{
return fontColor;
}
set
{
fontColor = value;
}
}
public Point old
{
get
{
return Start;
}
set
{
Start = value;
}
}
public Point cur
{
get
{
return End;
}
set
{
End = value;
}
}
public string Rand
{
get
{
return randValue;
}
set
{
randValue = value;
}
}
}
SOLVED: I was missing these lines in my mouse move method:
m.Start = new Point(deltaStart.X + e.Location.X, deltaStart.Y + e.Location.Y);
m.End = new Point(deltaEnd.X + e.Location.X, deltaEnd.Y + e.Location.Y);
You should move stuff in Form1_MouseMove instead of Form1_MouseUp.
Find the element you want to move in the Arraylist and assign it new position.
Redraw the element.
Also you should use IList<DrawingData> instead of ArrayList
I Can't find any solution how to reset the index when last file has been opened.
I have a mediaelement that reads images from a listbox and when last image has been played I want it to restart. Like a repeatable Mediaelement playlist.
Please help, I really need help with this one.
Dictionary<string, string> Listbox1Dict = new Dictionary<string, string>();
public static List<string> images = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" }; // Bildtyper som stöds
public static List<string> movies = new List<string> { ".WMV", ".WAV", ".SWF", ".MP4", ".MPG", ".AVI" }; // Filmtyper som stöds
List<string> paths = new List<string>();
DispatcherTimer dispatcherTimer = new DispatcherTimer();
DispatcherTimer NextImageTimer = new DispatcherTimer();
int x = 20; //Ställa in antal sekunder per bild
private int currentSongIndex = -1;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
private void dispatch()
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, x);
}
private void ShowNextImage()
{
if (currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
currentSongIndex++;
var selected = Listbox1.Items[currentSongIndex];
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
if (images.Contains(System.IO.Path.GetExtension(s).ToUpperInvariant()))
{
if (currentSongIndex < Listbox1.Items.Count)
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
mediaElement1.StretchDirection = StretchDirection.Both;
mediaElement1.Stretch = Stretch.Fill;
dispatcherTimer.Start();
}
}
else if (movies.Contains(System.IO.Path.GetExtension(s).ToUpperInvariant()))
{
if (currentSongIndex < Listbox1.Items.Count)
{
dispatcherTimer.Stop();
mediaElement1.Visibility = Visibility.Visible;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
mediaElement1.StretchDirection = StretchDirection.Both;
mediaElement1.Stretch = Stretch.Fill;
}
}
}
}
Cant you do something like:
private void ShowNextImage()
{
if (currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
if (currentSongIndex == ListBox1.Items.Count)
{
currentSongIndex = 0;
}
currentSongIndex++;
....
}
I apply some LinearGradientBrush animation to MediaElement and after this video is freezing.
I try to reset it via Player1.OpacityMask = null; but no joy.
By the way if I animate Opacity of the MediaElement then video shows good as usually.
Any clue what's up? How to fix the video freezing after applying LinearGradientBrush animation to MediaElement ?
Thank you!
/// <summary>
/// Interaction logic for WipeTransition.xaml
/// </summary>
public partial class WipeTransition
{
public WipeDirections Direction { set; get; }
public TimeSpan Duration = TimeSpan.FromSeconds(2);
public bool StopPrevPlayerOnAnimationStarts;
Random rdm = new Random(1);
bool isPlayer1;
public WipeTransition()
{
InitializeComponent();
try
{
Loaded += WipeTransition_Loaded;
SizeChanged += WipeTransition_SizeChanged;
Player1.CacheMode = new BitmapCache();
Player1.LoadedBehavior = MediaState.Manual;
Player2.CacheMode = new BitmapCache();
Player2.LoadedBehavior = MediaState.Manual;
Direction = WipeDirections.RandomDirection;
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
isPlayer1 = true;
}
catch (Exception)
{
}
}
void WipeTransition_SizeChanged(object sender, SizeChangedEventArgs e)
{
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
}
void WipeTransition_Loaded(object sender, RoutedEventArgs e)
{
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
}
public void Start(Uri uri)
{
try
{
Debug.WriteLine("************** START ANIMATION ***************************************");
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
// We start to Animate one of the Player is on BACK
if (isPlayer1)
{
if (StopPrevPlayerOnAnimationStarts)
Player2.Stop();
Canvas.SetZIndex(Player2, 49);
Canvas.SetZIndex(Player1, 50);
Player1.Source = uri;
Debug.WriteLine("Player1 - ANIMATE");
WipeAnimation(Player1);
}
else // Player2
{
if (StopPrevPlayerOnAnimationStarts)
Player1.Stop();
Canvas.SetZIndex(Player1, 49);
Canvas.SetZIndex(Player2, 50);
Player2.Source = uri;
Debug.WriteLine("Player2 - ANIMATE");
WipeAnimation(Player2);
}
}
catch (Exception)
{
}
}
public void WipeAnimation(FrameworkElement ObjectToAnimate)
{
try
{
LinearGradientBrush OpacityBrush = new LinearGradientBrush();
#region Setup Wipe Direction
switch (Direction)
{
case WipeDirections.RightToLeft:
OpacityBrush.StartPoint = new Point(1, 0);
OpacityBrush.EndPoint = new Point(0, 0);
break;
case WipeDirections.LeftToRight:
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(1, 0);
break;
case WipeDirections.BottomToTop:
OpacityBrush.StartPoint = new Point(0, 1);
OpacityBrush.EndPoint = new Point(0, 0);
break;
case WipeDirections.TopToBottom:
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(0, 1);
break;
case WipeDirections.RandomDirection:
#region
int randomValue = rdm.Next(0, 3);
if (randomValue == 0)
{
OpacityBrush.StartPoint = new Point(1, 0);
OpacityBrush.EndPoint = new Point(0, 0);
}
else if (randomValue == 1)
{
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(0, 1);
}
else if (randomValue == 2)
{
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(1, 0);
}
else if (randomValue == 3)
{
OpacityBrush.StartPoint = new Point(0, 1);
OpacityBrush.EndPoint = new Point(0, 0);
}
#endregion
break;
}
#endregion
GradientStop BlackStop = new GradientStop(Colors.Black, 0);
GradientStop TransparentStop = new GradientStop(Colors.Transparent, 0);
if (FindName("TransparentStop") != null)
UnregisterName("TransparentStop");
RegisterName("TransparentStop", TransparentStop);
if (FindName("BlackStop") != null)
UnregisterName("BlackStop");
this.RegisterName("BlackStop", BlackStop);
OpacityBrush.GradientStops.Add(BlackStop);
OpacityBrush.GradientStops.Add(TransparentStop);
ObjectToAnimate.OpacityMask = OpacityBrush;
Storyboard sb = new Storyboard();
DoubleAnimation DA = new DoubleAnimation() { From = 0, To = 1, Duration = Duration };
DoubleAnimation DA2 = new DoubleAnimation() { From = 0, To = 1, Duration = Duration };
sb.Children.Add(DA); sb.Children.Add(DA2);
Storyboard.SetTargetName(DA, "TransparentStop");
Storyboard.SetTargetName(DA2, "BlackStop");
Storyboard.SetTargetProperty(DA, new PropertyPath("Offset"));
Storyboard.SetTargetProperty(DA2, new PropertyPath("Offset"));
sb.Duration = Duration;
sb.Completed += sb_Completed;
sb.Begin(this);
if (isPlayer1)
{
Player1.Play();
}
else // Player2
{
Player2.Play();
}
}
catch (Exception)
{
}
}
void sb_Completed(object sender, EventArgs e)
{
if (isPlayer1)
{
Player1.OpacityMask = null;
isPlayer1 = false;
Player2.Stop();
Player2.Source = null;
}
else // Player2
{
Player2.OpacityMask = null;
isPlayer1 = true;
Player1.Stop();
Player1.Source = null;
}
Debug.WriteLine("************** END ANIMATION ***************************************");
}
public void Stop()
{
if (Player1.IsEnabled)
Player1.Stop();
if (Player2.IsEnabled)
Player2.Stop();
}
}
UPDATE:
The same problem happens after I apply shader effect. So video goes well before it and after this it is jumping/freezing. It seems that we have somehow to reset MedieElement or?
private void Button_Click_1(object sender, RoutedEventArgs e)
{
TransitionEffect[] effectGroup = transitionEffects[1];
TransitionEffect effect = effectGroup[1];
DoubleAnimation da = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(2.0)), FillBehavior.HoldEnd);
da.AccelerationRatio = 0.5;
da.DecelerationRatio = 0.5;
da.Completed += da_Completed;
effect.BeginAnimation(TransitionEffect.ProgressProperty, da);
VisualBrush vb = new VisualBrush(this.Player1);
vb.Viewbox = new Rect(0, 0, this.Player1.ActualWidth, this.Player1.ActualHeight);
vb.ViewboxUnits = BrushMappingMode.Absolute;
effect.OldImage = vb;
this.Player1.Effect = effect;
}