change image.source when tapped - c#

I'm a novice programmer so don't be brutal.
I'm making a game for Windows Store, and I want to animate a run cycle. I made many GIF animations but all have BLACK background, and I need it transparent. So I've decided to make a run cycle using DispatcherTimer. Everything works fine, but the images don't change :/
void timer_Tick(object sender, object e)
{
numer++;
if (numer > 8) numer = 1;
hero.Source.Equals("Assets/Anim/" + nazwa + numer + ".png");
}
Also, When I TAP a different image, it should change the image and other images, but it doesn't... what is wrong?
bool sun = true;
private void Image_Tapped(object sender, TappedRoutedEventArgs e)
{
sun = !sun;
if (sun == false)
{
Image1.Source.Equals("moon.png");
Image2.Source.Equals("ON.png");
}
else
{
Image1.Source.Equals("sun.png");
Image2.Source.Equals("OFF.png");
}
}
The xaml works fine, as the images are shown.
I have checked this question:
ImageTools on Windows Phone 8, changing ImageSource and DataContext
but I get loads of errors. I don't seem to understand how the property changed works.

it seems to be a small mistake. You are using the wrong method.
Image.Source.Equals()
is a boolean method that simply compares the current source with the "source" you give as arguement and will return true or false based on the comparison.
But what you want is to set the source of the image.
So you need to use:
Image1.Source = new BitmapImage(new Uri("moon.png", UriKind.RelativeOrAbsolute));
This will set the source of the Image to the new image you want.

Assuming that "moon.png" is in the main folder in your solution, the two solutions both work:
BitmapImage tn = new BitmapImage();
tn.SetSource(Application.GetResourceStream(new Uri(#"moon.png", UriKind.Relative)).Stream);
Image1.Source = tn;
Or
Image1.Source = new BitmapImage(new Uri("moon.png", UriKind.Relative));

Related

Updating Image when the selection in ListBox changes - WPF

What I am trying to achieve is change the source of Image when I change the selection in Listbox.
I have a method called GetImageLink that fetches a web URL for the current selection and assigns it to ReferenceImageLink property. (I checked, link is updated when selection changes). But when I try to use this as a source for the Image it does nothing. The image is perpetually blank from start. Can someone please point me in the right direction? I am new to WPF so it is kind of a little confusing to me.
public static string ReferenceImageLink { get; set; }
private async void VariantListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ReferenceImageLink = null;
var selecteditem = sender as ListBox;
string item = selecteditem.SelectedItem as string;
await GetImageLink(item);
BitmapImage referenceBMP = new BitmapImage();
referenceBMP.BeginInit();
//ReferenceImageLink property changes as ListBox selection change, GetImageLink takes care of it.
referenceBMP.UriSource = new Uri(ReferenceImageLink, UriKind.Relative);
referenceBMP.CacheOption = BitmapCacheOption.OnLoad;
referenceBMP.EndInit();
ReferenceImageBox.Source = referenceBMP;
}
<Image Name="ReferenceImageBox" HorizontalAlignment="Left" Height="189" Margin="558,51,0,0" VerticalAlignment="Top" Width="230" />
Screenshot of the WPF app
making UriKind.Absolute solved my problem. Thanks
referenceBMP.UriSource = new Uri(ReferenceImageLink, UriKind.Absolute);

Click on image and show message box depending on the clicked place

I have this idea of this world map image and when I click a country on it, it shows information of that country in a MessageBox for example does anyone have an idea how to do that?
I have a rectangle and a button and when i click the button it shows the image in the rectangle but i thought if i use polygons to shape the country's but I'm a little stuck.
I would like to have every country apart and maybe that the borders light up when clicked
You can do this pretty easily using WPF:
Find a nice World Map in SVG format. I used this one from Wikipedia:
Download and install Inkscape then open the SVG you've just downloaded. Inkscape has a nice feature that makes it possible to save an SVG as a XAML.
Import the ViewBox from the XAML file into your WPF window/etc:
For each Path in the XAML you can add a MouseEnter/MouseLeave event handler or you can use the same one for all the Paths
Sample code:
private void CountryMouseEnter(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Aqua);
}
}
private void Country_MouseLeave(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Black);
}
}
Now it's just a matter of changing colors/showing MessageBoxes etc.
GitHub
My first thought: You could bind a command to the view that will be triggered by a click on a position. If you're using WPF you can bind command parameters to the command to get the x and y of your click...
After that you have to handle the content of your messagebox and the highlighting of the borders depending on the position xy.
have fun :D
Option 1
There is a project on Code Project that someone created that defines hotspots that are clickable with events. You could use that to overlay your map and define the hotspots where you need them.
C# Windows Forms ImageMap Control
Option 2
You could bind to the MouseUp Event on the Image and use the following to see if it is in a Rectangle
private void mapMouseUp(object sender, MouseEventArgs e) {
Rectangle rect1 = new Rectangle(0, 0, 100, 100);
Rectangle rect2 = new Rectangle(0, 100, 100, 100);
if (rect1.Contains(e.Location)) {
// Do your stuff
} else if (rect2.Contains(e.Location)) {
// Do your stuff
}
}

Change background image source on button click in wpf forms

My default background image is "lobby.jpg" and when I click the "Lights" button I want it to swap with "lobby1.jpg" and vice versa. These images are stored in "obj\Debug\Images\".
Also I'd like to implement relative(?) imagesource uris so that I can access the images on any machine (without using the whole uri, just the "obj\Debug\Images\").
Edit: So the main issue seems to be that I tried changing the window background without realising that it was getting "covered" by the grid background of the page. So what I did is I set the main window background to "lobby.jpg", I made the grid background invisible and used the code from the answer to swap between the 2 backgrounds.
You can use AppDomain basepath to exe (this is are simplest way)
var basePath= AppDomain.CurrentDomain.BaseDirectory;
var imageDirPath = $"{basePath}\\Images\\";
Example:
bool clicked = false;
private void button_Click(object sender, RoutedEventArgs e)
{
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var imageDirPath = $"{basePath}\\Images\\";
if (clicked)
image.Source = new BitmapImage(new Uri(imageDirPath+ "lobby.jpg"));
else
image.Source = new BitmapImage(new Uri(imageDirPath + "lobby1.jpg"));
clicked = !clicked;
}

Saving, Storing, Loading Photographs in Windows Phone

Good morning everyone!
I've been having some issues regarding photos in my Windows Phone app. I'm trying to take a photo and save it to a record, and then load it up again at a different point.
My idea is to take the photo using the code in this tutorial (http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006(v=vs.105).aspx)
In my constructor:
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
lower down..
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//System.Diagnostics.Debug.WriteLine(e.OriginalFileName);
//string imageLoc = e.OriginalFileName;
//Uri imageUri = new Uri(imageLoc, UriKind.RelativeOrAbsolute);
//StreamResourceInfo resourceInfo = Application.GetResourceStream(imageUri);
//Code I'm using just now which just displays the photograph
System.Windows.Media.Imaging.BitmapImage bmp2 = new System.Windows.Media.Imaging.BitmapImage();
bmp2.SetSource(e.ChosenPhoto);
myImage.Source = bmp2;
}
}
From my code, you can see that the commented out bit returns the location of the image which has just been taken, then attempts to load it up from there. However, when I try that, I get URI path exceptions and the like. What is going wrong here and what method should I use to remedy it?
I'd like to be able to add the file path to a record and then be able to load it back up elsewhere in my app.
Thanks for any help!

Silverlight Canvas Sizing within a ScrollViewer

I am making a Silverlight 4 website with C#. In one of the pages, I want to have two panels beside each other. On the left is a map control and on the right is an image. That is easy enough, but I also want to be able to click on the image and leave PushPin like objects (like the map) so I put the image in a canvas and just draw circles. The problem is that image can be fairly large and I need to be able to scroll the image. I tried several different ways of achieving this, but so far no luck.
The answers to the following post seemed to be like the way to go, but there must be updates to Silverlight that broke it: WPF: How to make canvas auto-resize?
A similar solution suggested making the Canvas from scratch, but I ran into the same problem.
Most of my attempts end in displaying as much of the image as possible on the screen, but no scroll bars (still greyed out) or the page just goes white when the image is loaded.
The following is how I am currently selecting the image to load:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files (*.png, *.jpg)|*.jpg;*.png";
if(dialog.ShowDialog() == true) {
BitmapImage bitmap = new BitmapImage();
FileStream stream = dialog.File.OpenRead();
bitmap.SetSource(stream);
TheImage.Source = bitmap;
}
There is probably be a nicer solution but this should do the trick.
I have created a small fixed size ScrollViewer that contains a Canvas and an image. I then used a behaviour to modify the size of the canvas to match the size of the image. The behaviour also handles the ImageOpened event to set the correct size of the image once the image is opened.
Here is the xaml:
<ScrollViewer Width="200" Height="200" HorizontalScrollBarVisibility="Auto">
<Canvas x:Name="TheCanvas">
<Image x:Name="TheImage">
<i:Interaction.Behaviors>
<Views:ResizeCanvasBehaviour Canvas="{Binding ElementName=TheCanvas}"/>
</i:Interaction.Behaviors>
</Image>
</Canvas>
</ScrollViewer>
Be sure to declare i as xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
and b matches the namespace where you place the behaviour.
Here is the code for the behaviour:
public class ResizeCanvasBehaviour : Behavior<Image>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SizeChanged += AssociatedObject_SizeChanged;
AssociatedObject.ImageOpened += AssociatedObject_ImageOpened;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SizeChanged -= AssociatedObject_SizeChanged;
AssociatedObject.ImageOpened -= AssociatedObject_ImageOpened;
}
private void AssociatedObject_ImageOpened(object sender, RoutedEventArgs e)
{
BitmapSource bitmapSource = AssociatedObject.Source as BitmapSource;
if (bitmapSource == null)
{
return;
}
AssociatedObject.Width = bitmapSource.PixelWidth;
AssociatedObject.Height = bitmapSource.PixelHeight;
Resize();
}
private void AssociatedObject_SizeChanged(object sender, SizeChangedEventArgs e)
{
Resize();
}
public Canvas Canvas
{
get { return GetValue(CanvasProperty) as Canvas; }
set { SetValue(CanvasProperty, value); }
}
public static readonly DependencyProperty CanvasProperty = DependencyProperty.Register(
"Canvas",
typeof(Canvas),
typeof(ResizeCanvasBehaviour),
new PropertyMetadata(null, CanvasPropertyChanged));
private static void CanvasPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ResizeCanvasBehaviour)d).OnCanvasPropertyChanged();
}
private void OnCanvasPropertyChanged()
{
if (Canvas != null)
{
Resize();
}
}
private void Resize()
{
if ((AssociatedObject != null) && (Canvas != null))
{
Canvas.Width = AssociatedObject.ActualWidth;
Canvas.Height = AssociatedObject.ActualHeight;
}
}
}
To load the image do something like this. I did this in code behind for speed but ideally you should put this in a view model and then data bind the image Source property in xaml:
BitmapImage bi = new BitmapImage();
bi.UriSource = new Uri("http://farm7.static.flickr.com/6149/5942401995_a5a3fd3919_z.jpg");
TheImage.Source = bi;
Turns out the very minimum that I needed to do was set the Width and Height of the canvas to the PixelWidth and PixelHeight of the BitmapImage instance.
This is what Paul was doing with his solution (in a little more complicated way), but for some reason the resize event handlers would not get called when a image was loaded locally.
I had tried several different suggested solutions, but I never got the results I was wanting. This was the only solution that seemed to work.

Categories

Resources