Fade In-Out for image in WPF - wpf

How can i implement FadeIn and then FadeOut image when i change image source like slide show. my images load from local and web and count of that is varaible.
Thankyou

You could write an extension method that fades out the image by animating its Opacity property to 0, then sets the Source property and finally animates the opacity back to 1.
public static void ChangeSource(
this Image image, ImageSource source, TimeSpan fadeOutTime, TimeSpan fadeInTime)
{
var fadeInAnimation = new DoubleAnimation(1d, fadeInTime);
if (image.Source != null)
{
var fadeOutAnimation = new DoubleAnimation(0d, fadeOutTime);
fadeOutAnimation.Completed += (o, e) =>
{
image.Source = source;
image.BeginAnimation(Image.OpacityProperty, fadeInAnimation);
};
image.BeginAnimation(Image.OpacityProperty, fadeOutAnimation);
}
else
{
image.Opacity = 0d;
image.Source = source;
image.BeginAnimation(Image.OpacityProperty, fadeInAnimation);
}
}

You can use WPF transition for this, please check at Here

Related

WPF issue with VisualBrush for Image while moving

I have Image and i have created visual brush for image when i move object form one point to another. but I don't see image on visual brush. if you see my rectangle, it suppose to show image.
See image : http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/e8833983-3d73-45e1-8af1-3bc27846441d
here is code:
internal static VisualBrush GetVisualBrushByObject(LabelObject obj, Rect objectRect, int quality, FlowDirection flowdirection)
{
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
Rect objectbounds = new Rect(0, 0, objectRect.Width, objectRect.Height);
if (obj is TextObject)
{
TextObject txtObj = obj.Clone() as TextObject;
DymoTextBlock txtBlock = txtObj.DymoTextBlock as DymoTextBlock;
objectbounds = new Rect(txtBlock.GetNaturalSize(txtBlock.GetFormattedText(flowdirection)));
}
if (obj is ImageObject)
{
drawingContext.DrawImage(((ImageObject)obj).Image, objectbounds);
}
LabelObject.RenderParams lrp = new LabelObject.RenderParams(drawingContext, new Common.Resolution(96, 96), false, objectbounds, flowdirection);
obj.Render(lrp);
VisualBrush vBrush = new VisualBrush();
vBrush.TileMode = TileMode.None;
vBrush.Stretch = Stretch.Fill;
if (obj is ImageObject)
{
vBrush.Opacity = 0.4;
}
drawingContext.Close();
vBrush.Visual = drawingVisual;
return vBrush;
}
pls help me
Thanks
If you are moving your image with Transforms(TranslateTransform), then you have to undo it for the visual brush phase.

Grid Background Image Opacity Animation

Created a simple jquery-nivo-like slider using wpf and want to add an animation between slides that fades the background, changes the background image, and finally fades back in the new background image. I was trying to do the following....I get no errors, background changes, but there wasn't any animation either...what am I doing wrong?
public void SetSlider(MyItem item)
{
//Fade out
DoubleAnimation fadeOutAnimation = new DoubleAnimation(0, TimeSpan.FromSeconds(3));
fadeOutAnimation.AutoReverse = false;
grdContent.Background.BeginAnimation(Brush.OpacityProperty, fadeOutAnimation);
//set background
ImageBrush bgBrush = new ImageBrush();
bgBrush.ImageSource = new BitmapImage(new Uri(item.ImageFile.SavedDirectoryAndFile, UriKind.Absolute));
grdContent.Background = bgBrush;
//Set title
txtTitle.Text = item.Title;
//set Summary
txtSummary.Text = item.Summary;
//Fade back in
DoubleAnimation fadeInAnimation = new DoubleAnimation(1, TimeSpan.FromSeconds(3));
fadeInAnimation.AutoReverse = false;
grdContent.Background.BeginAnimation(Brush.OpacityProperty, fadeInAnimation);
}
Figured it out... I had to apply the animation to the brush that was set in the background property...not the background property itself and I had to make some timing changes. Here is my final solution:
public void SetSlider(MyItem item)
{
//Create the fade out animation.
DoubleAnimation fadeOutAnimation = new DoubleAnimation(0, TimeSpan.FromMilliseconds(500));
fadeOutAnimation.AutoReverse = false;
//wait until the first animation is complete before changing the background, or else it will appear to just "fadeIn" with now fadeout.
fadeOutAnimation.Completed += delegate(object sender, EventArgs e)
{
//once the fadeout is complete set the new back ground and fade back in.
//Create a new background brush.
ImageBrush bgBrush = new ImageBrush();
bgBrush.ImageSource = new BitmapImage(new Uri(item.ImageFile.SavedDirectoryAndFile, UriKind.Absolute));
bgBrush.Opacity = 0;
//Set the grid background to the new brush.
grdContent.Background = bgBrush;
//Set the brush...(not the background property) with the animation.
DoubleAnimation fadeInAnimation = new DoubleAnimation(1, TimeSpan.FromMilliseconds(500));
fadeInAnimation.AutoReverse = false;
bgBrush.BeginAnimation(Brush.OpacityProperty, fadeInAnimation);
};
//Fade out..before changing the background.
var currentBackground = grdContent.Background;
currentBackground.BeginAnimation(Brush.OpacityProperty, fadeOutAnimation);
//Set title
txtTitle.Text = item.Title;
//set Summary
txtSummary.Text = item.Summary;
}
A simpler approach will be using Transitional's they have a sample project of image animation.
References:
xmlns:trans="clr-namespace:Transitionals;assembly=Transitionals"
xmlns:transc="clr-namespace:Transitionals.Controls;assembly=Transitionals"
xmlns:transt="clr-namespace:Transitionals.Transitions;assembly=Transitionals"
xmlns:refl="clr-namespace:System.Reflection;assembly=mscorlib"
<transc:TransitionElement x:Name="TransitionBox" Grid.Row="1" Content="{Binding
CurrentImage}">
<transc:TransitionElement.Transition>
<transt:TranslateTransition StartPoint="1,0" EndPoint="0,0"
Duration="0:0:0.6"/>
</transc:TransitionElement.Transition>
</transc:TransitionElement>
or use SlideShow Control it has if its an automatic Transition.
<transc:Slideshow.TransitionSelector>
<trans:RandomTransitionSelector>
<trans:RandomTransitionSelector.TransitionAssemblies>
<refl:AssemblyName Name="Transitionals" />
</trans:RandomTransitionSelector.TransitionAssemblies>
</trans:RandomTransitionSelector>
</transc:Slideshow.TransitionSelector>

Loading Images in background while not locking the files

My application loads a lot of images in a BackgroundWorker to stay usable. My Image control is bound to a property named "ImageSource". If this is null it's loaded in the background and raised again.
public ImageSource ImageSource
{
get
{
if (imageSource != null)
{
return imageSource;
}
if (!backgroundImageLoadWorker.IsBusy)
{
backgroundImageLoadWorker.DoWork += new DoWorkEventHandler(bw_DoWork);
backgroundImageLoadWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
backgroundImageLoadWorker.RunWorkerAsync();
}
return imageSource;
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
bitmap = new BitmapImage();
bitmap.BeginInit();
try
{
bitmap.CreateOptions = BitmapCreateOptions.DelayCreation;
bitmap.DecodePixelWidth = 300;
MemoryStream memoryStream = new MemoryStream();
byte[] fileContent = File.ReadAllBytes(imagePath);
memoryStream.Write(fileContent, 0, fileContent.Length);
memoryStream.Position = 0;
bitmap.StreamSource = memoryStream;
}
finally
{
bitmap.EndInit();
}
bitmap.Freeze();
e.Result = bitmap;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BitmapSource bitmap = e.Result as BitmapSource;
if (bitmap != null)
{
Dispatcher.CurrentDispatcher.BeginInvoke(
(ThreadStart)delegate()
{
imageSource = bitmap;
RaisePropertyChanged("ImageSource");
}, DispatcherPriority.Normal);
}
}
This is all well so far but my users can change the images in question. They choose a new image in an OpenDialog, the old image file is overwritten with the new and ImageSource is raised again which loads the new image with the same filename again:
public string ImagePath
{
get { return imagePath; }
set
{
imagePath= value;
imageSource = null;
RaisePropertyChanged("ImageSource");
}
}
On some systems the overwriting of the old file results in an exception:
"a generic error occured in GDI+" and "The process cannot access the file..."
I tried a lot of things like loading with BitmapCreateOptions.IgnoreImageCache and BitmapCacheOption.OnLoad. This raised Exceptions when loading them:
Key cannot be null.
Parameter name: key
If I try this without the BackgroundWorker on the UI thread it works fine. Am I doing something wrong? Isn't it possible to load the images in the background while keeping the files unlocked?
Well, it seems all of the above works. I simplified the example for the question and somehow on the way lost the problem.
The only difference I could see in my code is that the loading of the image itself was delegated to a specific image loader class which somehow created the problem. When I removed this dependency the errors disappeared.

WPF: Get specify image from touch

I was added picture as a children to layer called "canvas". By the following code:
if (addChild)
{
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(path, UriKind.Absolute);
src.EndInit();
i.Source = src;
i.Width = 200;
i.IsManipulationEnabled = true;
double rotAngle = Rand.GetRandomDouble(-3.14/4, 3.14/4);
i.RenderTransform = new MatrixTransform(Math.Cos(rotAngle), -Math.Sin(rotAngle),
Math.Sin(rotAngle), Math.Cos(rotAngle), Rand.GetRandomDouble(0, this.Width - i.Width), Rand.GetRandomDouble(0, this.Height - i.Width));
canvasImages.Add(i);
canvas.Children.Add(i);
Canvas.SetZIndex(i, canvas.Children.Count-1);
addedFiles.Add(path);
maxZ++;
}
Here is the problem. I'm trying to make an event called "canvas_TouchDown" which can detect the specify picture when I touched it so that it will get the center of that image object.
List<Image> canvasImages = new List<Image>();
private void canvas_TouchDown(object sender, TouchEventArgs e)
{
foreach (Image canvasImage in canvasImages)
{
if (canvasImage.AreAnyTouchesCaptured == true)
{
System.Diagnostics.Debug.WriteLine("I found image that you touch");
}
}
}
However, there is nothing happened. I also try to use PersistId property but it doesn't work. Have any suggestion?
Regard,
C.Porawat
If you are adding the image to the canvas, touching it and expecting the canvas to receive the touch you will be disappointed. You should either listen to "touch down" on the image or "preview touch down" on the canvas.

WPF, Image MouseDown Event

I have an control with a mouse down event where Id like to chnage the Image when the image is clicked. But I cant seem to alter ANY of the images properties in the event.
Event
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
BitmapImage bitImg = new BitmapImage();
bitImg.BeginInit();
bitImg.UriSource = new Uri("./Resource/Images/Bar1.png", UriKind.Relative);
bitImg.EndInit();
((Image)sender).Source = null;
((Image)sender).Width = 100;
((Image)sender).Visibility = Visibility.Hidden;
}
The event does fire, and even the .Visibility property does not alter the image and make it hidden.
What am I doing wrong?
Assuming the file is in your application, you need to use the Pack URI scheme:
var img = sender as Image;
BitmapImage bmp = new BitmapImage(new Uri("pack://application:,,,/Resources/Images/Bar1.png"));
img.Source = bmp;
In the above example, this would indicate a subfolder in your project of Resources/Images.

Resources