A note: I've just started approaching Windows 8 so, please be gentle. I want to set a background image to a canvas:
private void InsertImage(object sender, RoutedEventArgs e) {
var uri = new System.Uri("inkpen:///Assets/01.jpeg");
var photo_background = new ImageBrush {
ImageSource = new BitmapImage {
UriSource = uri
}
};
panelcanvas.Background = photo_background;
}
xaml:
<Canvas Name="panelcanvas" Background="White" Margin="47.5,57,327.5,153"/>
The background changes from white to black and the image doesn't load. How can I fix this?
Thank you.
The problem was the Uri
ms-appx:///Assets/01.jpeg
fixed it
http://msdn.microsoft.com/en-us/library/windows/apps/hh781215.aspx
Related
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);
This question already has an answer here:
how can I set a background image in code?
(1 answer)
Closed 7 years ago.
How can I change grid background image of clicked button? I tried this code but it didn't work. I need help.
Code:
WpfApplication5.Properties.Settings.Default.GridImage = "Pictures\file.jpg";
Background can be set by using ImageBrush:
var imgBrush = new ImageBrush();
imgBrush.ImageSource = new BitmapImage(new Uri(#"Pictures\file.jpg", UriKind.Relative));
myGrid.Background = imgBrush;
When using relative path, you need to have Pictures folder with file.jpg in bin\Debug folder.
Like this.You should set Background of Button
<Grid>
<Button Name="button1" Click="button1_Click">
</Button>
</Grid>
private void button1_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("image path", UriKind.Relative);
BitmapImage img = new BitmapImage(uri);
button2.Background = new ImageBrush(img );
}
I'm working on a Universal App in which I'm trying to generate a bitmap from a selection so that I can show a fancy animation of the selected object moving from inside a SettingsFlyout, to a new location on the screen while the SettingsFlyout with the listview is transitioned away to a "details" one.
I've seen this code suggested elsewhere but it doesn't seem to work. I get a System.ArgumentException followed by "Value does not fall within the expected range." at the RenderAsync call. any Idea why that's happening? stepping through the code reveals the ListViewItem is properly found, but rendering it doesn't work. I saw another mention of ItemContainerGenerator but it generated a NullReferenceException.
private async void AnimateSelection(object sender, SelectionChangedEventArgs e)
{
var container =
(sender as ListView).ContainerFromItem((sender as ListView).SelectedItem);
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(container as FrameworkElement);
// go on to animate this by copying it to another grid
}
Anybody tried this before? What I want to do is to simple copy the Selected Item of a listview and use it on another Grid. let me know if I need to edit the question with more information.
EDIT:
Upon a suggestion from another dev , I tried rendering the pageRoot stackpanel and another TextBox from the same page and that failed too. I think the issue is with the render itself - can I substitute this code with something else?
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(container as FrameworkElement);
EDIT:
dev suggested dispatcher could be an issue, turns out dispatcher is handled differently in Universal Apps, so I tried to use it through that - no change
var container =
(sender as ListView).ContainerFromItem((sender as ListView).SelectedItem);
await this.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(container as FrameworkElement);
var vm = this.DataContext as PersonViewModel;
vm.TransitionImageSource = bitmap;
});
Without a repro of your code I can't say what's wrong but there's nothing fundamentally wrong with your approach.
The following works:
Create a new blank universal app.
Share the MainPage between both targets
Add this XAML:
<StackPanel>
<TextBlock>Some text</TextBlock>
<Button Click="ChangeColor_OnClick">change color</Button>
<ListBox x:Name="ListBox">
<ListBoxItem>item 1</ListBoxItem>
<ListBoxItem>item 2</ListBoxItem>
<ListBoxItem>item 3</ListBoxItem>
</ListBox>
<Button Click="TakeScreenshot_OnClick">take screenshot</Button>
<Button Click="TakeScreenshotOfSelected_OnClick">take screenshot of just selected item</Button>
<Image x:Name="DisplayedScreenshot" Height="200" />
</StackPanel>
Add this code behind:
private void ChangeColor_OnClick(object sender, RoutedEventArgs e)
{
var rand = new Random();
this.Background = new SolidColorBrush(new Color { A = 255, R = (byte)rand.Next(1, 255), G = (byte)rand.Next(1, 255), B = (byte)rand.Next(1, 255) });
}
private async void TakeScreenshot_OnClick(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(this as FrameworkElement);
this.DisplayedScreenshot.Source = rtb;
}
private async void TakeScreenshotOfSelected_OnClick(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(this.ListBox.SelectedItem as UIElement);
this.DisplayedScreenshot.Source = rtb;
}
I solved this issue by changing the SettingsFlyout to a UserControl and faking the effects of the SettingsFlyout which breaks the standard behaviour in the process. Looks like this is not really an Answer but there certainly IS a problem with SettingsFlyout and needs to be investigated thoroughly
Thanks Matt
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));
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.