Recently I've been strugling with setting the Setting the source of WPF Image control inside code.
I've tried something like:
Image.Source = new BitmapImage(new Uri(#"/hrc.Hands;component/Images/BlueFolder.png", UriKind.RelativeOrAbsolute));
But it doesn't seem to work and thorws Object reference not set to an instance of an object exception. Here's the screenshot of the path to my image inside hierachy:
You can use..
var imageSource = new Uri(#"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Images/BlueFolder.png", UriKind.Absolute);
Image.Source = imageSource;
Also, make sure that BlueFolder.png is set as a Resource. Right click the image, and select Properties to do this.
Related
I am trying add a background image using the image property in button. The issue I'm facing is that i can't set StreamImageSource as button background. I encountered the error given below if I try to do so.
The Code I use to set Image:
ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes));
Button Icon = new Button ();
Icon.Image = iconsource ;
The Error I encounter:
Error CS0266: Cannot implicitly convert type 'Xamarin.Forms.ImageSource' to 'Xamarin.Forms.FileImageSource'. An explicit conversion exists (are you missing a cast?)
ImageSource.FromStream () returns a StreamImageSource (see docs). Button.Image accepts only FileImageSource (see docs).
It means that what you're trying to achieve won't work, no matter how hard you try to cast one into the other.
Button.Image will accept images stored as resources in your platform projects, and loaded either with:
Icon.Image = ImageSource.FromFile ("foobar.png");
or
Icon.Image = "foobar.png";
The accepted answer is true that you can't cast StreamImageSource to FileImageSource, I think that the real question is about how to share images in a PCL and use them on a button, just like one would when creating an Image forms control.
The answer is to have a Grid which contains both a Button and an Image object, where the Image overlaps the Button.
For example, the C# code might look like this:
ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
Button iconButton = new Button ();
iconButton.VerticalOptions = LayoutOptions.FillAndExpand;
iconButton.HorizontalOptions = LayoutOptions.FillAndExpand;
var image = new Image();
image.Source = imageSource;
// So it doesn't eat up clicks that should go to the button:
image.InputTransparent = true;
// Give it a margin so it doesn't extend to the edge of the grid
image.Margin = new Thickness(10);
var grid = new Grid();
// If we don't set a width request, it may stretch horizontally in a stack
grid.WidthRequest = 48;
// Add the button first, so it is under the image...
grid.Children.Add(iconButton);
// ...then add the image
grid.Children.Add(image);
You may have to play with the sizes and thickness values but this should get you a clickable button with an icon.
As of Xamarin.Forms 3.4.0 you can now use ImageButton. You can use embedded images by using an extension method explained in this MS document
Careful with upper- and lowercase in filenames.
I was wondering, why my button-images were shown properly on the simulator, but not on my iPhone.
On the device the filename must match exactly, the simulator doesn't care about upper- and lowercase in filenames.
I use this and it works
var imageA = new Image();
imageA.Source=(FileImageSource)ImageSource.FromFile(allergeneLocation)};
or
var imageA = new Image()
{
BackgroundColor = Color.Teal,
Source = (FileImageSource)ImageSource.FromFile(allergeneLocation)},
};
Here is what I tried:
Button refreshBut = new Button
{
Image = (FileImageSource)
(ImageSource.FromFile("refreshBut.png"))
};
While it compiles I then get an unhandled null reference exception with the description: Object reference not set to an instance of an object. I am not sure if this will help anyone else try to solve this but I am at the same wall.
Excuse the novice question, but I am just learning WPF.
I have an image that I've set the build action to be "Resource"
If I set it as the Window Icon in the XAML it works just fine.
like this:
Window ... Icon="Images/MyIco.png"
But, if I try to set it as the source for an Image, I get an exception the resource is not found:
Uri uri = new Uri("pack://application:,,,/Images/MyIco.png"); // This does not work
img.Source = BitmapFrame.Create(uri);
What am I doing wrong in the code above?
Make sure your path is correct, if true, u can try this code to load your image
//tmp is your path
BitmapImage img = new BitmapImage(new Uri(tmp, UriKind.Relative));
img.CreateOptions = BitmapCreateOptions.None;
img.ImageOpened += img_ImageOpened;
void img_ImageOpened(object sender, RoutedEventArgs e)
{
WriteableBitmap wbm = new WriteableBitmap((BitmapImage)sender);
}
Ex: my path is "/Assets/sizes/background/bg_02.png"
Image myImage3 = new Image();
BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri(#"C:\Users\User\Desktop\Awesomeness\PicProgram\Program\bin\Debug\flower.png", UriKind.Relative);
bi3.EndInit();
myImage3.Stretch = Stretch.Fill;
myImage3.Source = bi3;
I was wondering how I get myImage3 added to the window.
I've tried this.content.add.myImage3 or this.add(myImage3) and other variations none seem to work.
Any suggestions?
Thanks
Seems like a basic wpf usage question, although doing something that is simple in xaml can get a bit complex in code behind.....
You have to add your image to some panel or content control in your window, not the window itself. So if there is a grid in your window, give the grid a name like m_grid, then do m_grid.children.add(myImage3).
When the Image's Source property is set the following way, the picture is taken from /Images/down.png.
How would I do the same thing programmatically?
<Image x:Name="myImg" Source="/MyProject;component/Images/down.png" />
The following would not work, since Image.Source property is not of a string type.
myImg.Source = "/MyProject;component/Images/down.png";
Try this:
BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
myImg.Source = new BitmapImage(new Uri(#"component/Images/down.png", UriKind.RelativeOrAbsolute));
Don't forget to set Build Action to "Content", and Copy to output directory to "Always".
Try to assign the image that way instead:
imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, #"/Assets/favorited.png"));
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}
LOGO refers to your image
Hoping to help anyone. :)
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
try this
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(#"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
After several attempts to change the background of a button, and getting errors of casting and things like that I finnaly got to this point:
Uri dir = new Uri("red_flag.png",UriKind.RelativeOrAbsolute);
ImageSource source = new System.Windows.Media.Imaging.BitmapImage(dir);
ImageBrush bru = new ImageBrush();
bru.ImageSource=source;
bru.Opacity = 100;
This code does not generate errors, but I can't see the changes when I call:
button1.background = bru;
It just makes anything! :(
found the answer myelf after reading Mick's answer, I share with you what I did:
Uri dir = new Uri("red_flag.png", UriKind.Relative);
ImageSource source = new System.Windows.Media.Imaging.BitmapImage(dir);
Image image = new Image();
image.Source = source;
StackPanel stack = new StackPanel();
stack.Children.Add(image);
myButton.Content = stack;
Thanks for your help
Update 1:
For best results set the padding property of your button to 0 (in each of the cases) so the image can resize automatically to fill all the button, please note this could hide your actual content, in my case this was what I wanted.
If this code is part of the click event handler for the same button you will have this problem.
Peter Torr explains why here and offers a solution.
Why can't I change the Background of my Button on a Click event?