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.
Related
I'm working on making a memory game in C# using borders with images and changing their source. Changing the first source works correctly, however after the second flip I call a function to check if they match before flipping them to a correct or hidden image. I've been having an issue with the second image because the events I've tried call before the function has exited so the second image only shows the hidden image. Is there an event I can call to check if the image has loaded before exiting?
//border mousedown event
private void Border_MouseDown(object sender, MouseButtonEventArgs e)
{
//flip the image over
Border picBorder = sender as Border;
picBorder.IsEnabled = false; //disable the border so they can't click it again
int index = Int32.Parse(Regex.Match(picBorder.Name, #"\d+").Value); //get border #
BitmapImage car = new BitmapImage(carImages[index]);
picBorder.Child = new Image { Source = car};
picBorder.IsEnabled = false;
//Storing border locations for checking later
borderLocations[currentCarsFlipped] = picBorder;
currentCarsFlipped++;
}
Once CurrentCarsFlipped == 2, I need to check if there is a match. Currently, I have checkWin() which looks like it will work, but is hard to debug when you can only see 1 image for every 2 clicks
use a Boolean variable ,
False if not updated and true after update, then you can check
I want to animate lives tiles in UAP applications. But I am getting this exception:
Cannot implicitly convert type 'NotificationsExtensions.Tiles.TileImageSource' to 'string'.
I am using this code:
TileBindingContentAdaptive largebindingContent = new TileBindingContentAdaptive()
{
PeekImage = new TilePeekImage()
{
Source = new TileImageSource("Assets/Apps/Hipstame/hipster.jpg")
},
Children =
{
new TileText() {Text =Description, Wrap = true, Style = TileTextStyle.BodySubtle}
}
};
How can I animate my live tiles?
Cannot implicitly convert type 'NotificationsExtensions.Tiles.TileImageSource' to 'string'.
The reason you are getting this exception is because as of May 2016 NotificationsExtensions received some updates where there have been changes made to TileBackgroundImage and TilePeekImage. You can see the details of these changes here in the msdn update post.
Specifically, the property type for Source changed from TileImageSource to string. This change means that you need to change the way you are setting Source. Note in the code below (yours, which I modified) where the Source is simply a string. This should resolve the exception you are getting.
TileBindingContentAdaptive largebindingContent = new TileBindingContentAdaptive()
{
PeekImage = new TilePeekImage()
{
Source = "Assets/Apps/Hipstame/hipster.jpg"
},
Children =
{
new TileText()
{
Text = Description,
Wrap = true,
Style = TileTextStyle.BodySubtle
}
}
};
As far as animating your live tiles there are a variety of things you can do and I cannot give any specific advice unless you specify what you want to do with your tiles. For example, if you want to cycle through images in your live tile you can take a look at this example here for cycling multiple images with an animation through a live tile. You can also refer to the msdn Adaptive Tile Templates documentation if you want to read through in more detail about what else you can do with your tiles.
I got this issue with displaying a image that i allready have added as a resource. I am guessing i am missing something vital but i cant find what it is. I am hoping that someone has a better idea of what i am doing wrong atm.
I have added an .bmp image into the solutiontree and changed the build action properties of that image to Embedded resource but i cant figure out how to call that image from the pipe?
as the user clicks a button the image should be sent to the imagebox, the code i have written so far looks like this:
this is ofs only the button_click code:
private void button1_Click(object sender, EventArgs e)
{
//Show image in the picturebox of selected cake
Image image = Image.FromFile(fruitcake.jpg);
pictbox.Image = image;
pictbox.Height = 163;
pictbox.Width = 223;
choice = 1;
lblCookiesPerGram.Text = string.Empty;
}
Anyone has an idea of what i am doing wrong or can i do this in another war? mind thou its 4 buttons the user clicks and there is a image for each one ;)
//Regards
If you go to your Solution - Properties window and select the Resources tab and add the image through this manager, then the images can be directly referenced like this:
Image image = Properties.Resources.fruitcake;
To retrieve an image from a resource, you can do something like:
using (Stream imgStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(
"MyNamespace.resources.fruitcake.jpg"))
{
var image = new Bitmap(imgStream);
pictBox.Image = image;
pictBox.Height = image.Height;
pictBox.Width = image.Width;
}
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).
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?