Adding background Image to a button using PhotoChooserTask - windows-phone-7

I'm trying to insert image in a button through photochoosertask
but on casting btnSelectImage.Content as Image it gives null
can you please help me out
void photoChooserTask_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Image contentImage = btnSelectImage.Content as Image;
if (contentImage != null)
{
contentImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(e.OriginalFileName));
}
}
}

void photoChooserTask_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
contentImage.Source = bitmap;
}
}
Try this.
I am not sure what you xaml looks like. You'll have to use it this way
<Button>
<Image x:Name="contentImage" />
</Button>

Related

How to create bitmap from string text with SkiaSharp

I created an entry where you type in a value, but now I want to create a bitmap with the text of an entry. When I got the bitmap, I can load it in SkiaSharp and use BitmapModifiers on it.
Is this possible?
I would recommend you to go through these examples on github.
Dummy sample could look like this:
This is xaml page:
<StackLayout>
<Entry x:Name="InputText" />
<Button Text="Create Bitmap" Clicked="Button_Clicked" />
</StackLayout>
Codebehind:
SKBitmap helloBitmap;
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear(SKColors.Aqua);
canvas.DrawBitmap(helloBitmap, 0, 0);
}
private void Button_Clicked(object sender, EventArgs e)
{
CreateBitmapFromText(InputText.Text);
}
private void CreateBitmapFromText(string text)
{
// Create bitmap and draw on it
using (SKPaint textPaint = new SKPaint { TextSize = 48 })
{
SKRect bounds = new SKRect();
textPaint.MeasureText(text, ref bounds);
helloBitmap = new SKBitmap((int)bounds.Right,
(int)bounds.Height);
using (SKCanvas bitmapCanvas = new SKCanvas(helloBitmap))
{
bitmapCanvas.Clear();
bitmapCanvas.DrawText(text, 0, -bounds.Top, textPaint);
}
}
SKCanvasView canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurface;
Content = canvasView;
}

How to save the final photo in Forms.Image to local in xamarin forms

I'm making an app for android with Xamarin forms where the user would select a photo from their library, add a White border to make it a square, then save it. I'm stuck at the saving part, can't figure it out
I am using the normal Xamarin.Forms.Image control
<Image HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"
BackgroundColor="Transparent"
Grid.Column="0"
Grid.Row="0"
x:Name="imgViewer"/>
this is how I select the photo
async void tbAdd_Activated(object sender, System.EventArgs e)
{
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
imgViewer.Source = ImageSource.FromFile(file.FilePath);
imgViewer.BackgroundColor = Color.White;
}
}
But then I have a save button to save that final image with the border to the camera roll but I have no idea how to save it, I've searched everywhere but can't seem to find!
Anyone knows how to do that ?
You will have to specific codes in iOS and android to save the images and Also add required permissions in iOS by adding this key to info.Plist file
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME)</string>
Android :
MediaStore.Images.Media.InsertImage(Application.Context.ContentResolver, [YourFileName],
System.IO.Path.GetFileName([YourFileName]), string.Empty);
iOS :
var imageSource = CGImageSource.FromUrl(NSUrl.FromFilename( [YourFileName]));
UIImage.FromImage(imageSource.CreateImage(0, null), 1, imageOrientation)
.SaveToPhotosAlbum((image, error) => { // handle success & error here... });
You can check this link for more info.
You can save the image by the following code:
void save_Activated(object sender, System.EventArgs e)
{
if (file != null)
{
byte[] imageBytes;
var FileImage = new Image();
string base64;
using (var fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
base64 = Convert.ToBase64String(buffer);
}
imageBytes = Convert.FromBase64String(base64);
File.WriteAllBytes(filename, imageBytes);
}
So the full code is like this:
string documentsFolder;
string filename;
FileData file;
ImageSource imageSource;
public MainPage()
{
InitializeComponent();
documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(documentsFolder, "myfile.jpg");
}
async void tbAdd_Activated(object sender, System.EventArgs e)
{
file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
imgViewer.Source = ImageSource.FromFile(file.FilePath);
imgViewer.BackgroundColor = Color.White;
imageSource = imgViewer.Source;
}
}
void save_Activated(object sender, System.EventArgs e)
{
if (file != null)
{
byte[] imageBytes;
var FileImage = new Image();
string base64;
using (var fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
base64 = Convert.ToBase64String(buffer);
}
imageBytes = Convert.FromBase64String(base64);
File.WriteAllBytes(filename, imageBytes);
}
}
And the xamal is:
<Button Text="AddImage" Clicked="tbAdd_Activated">
</Button>
<Button Text="SaveImage" Clicked="save_Activated">
</Button>
<Image HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"
BackgroundColor="Transparent"
Grid.Column="0"
Grid.Row="0"
x:Name="imgViewer"/>

CustomRenderer iOS for button TouchUpInside change background

I'm trying to write a CustomRenderer for iOS through which I want to change the BackgroundColor of the button when the user touches it. So far i got this:
public class BtnRendereriOS : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.BackgroundColor = UIColor.FromRGB(3, 169, 244);
Control.Layer.CornerRadius = 0;
}
Control.TouchUpInside += (sender, UIButton) => {
Control.BackgroundColor = UIColor.Brown;
};
}
}
Its not working however. I guess there needs to be some sort of eventhandler in order to make this possible.
The background colors needs to be initially set (if not the default color), then you need to set it back to that same color on TouchUpInside and TouchUpOutside. On TouchDown, set it to the color that you wish it to be while the button is being pressed.
Toggle background color:
if (Control != null)
{
void BackgroundNormalState(object sender)
{
(sender as UIButton).BackgroundColor = UIColor.Green;
}
BackgroundNormalState(Control);
Control.TouchUpInside += (object sender, EventArgs e) =>
{
BackgroundNormalState(sender);
};
Control.TouchUpOutside += (object sender, EventArgs e) =>
{
BackgroundNormalState(sender);
};
Control.TouchDown += (object sender, EventArgs e) =>
{
(sender as UIButton).BackgroundColor = UIColor.Red;
};
}
Update:
Can i change my textcolor through this methodgroup as well?
There are is a SetTitleColor where you can assign different colors to the different UIControlState values, Normal and Highlighted are the ones to start with:
Control.SetTitleColor(UIColor.Red, UIControlState.Normal);
Control.SetTitleColor(UIColor.Green, UIControlState.Highlighted);

Changing the image on a button when clicked xaml

im trying to change between two images of a button when the same button is clicked
my xaml code is
<Button x:Name="BidderOne"
Click="BidderOne_Click" Height="5"
Grid.Row="2"
BorderBrush="#FFE7E3E3"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="350,0,0,280"
>
<Button.Template>
<ControlTemplate>
<Image x:Name="BidderOneImage"
Source="/Assets/Star.png"
Width="50"/>
</ControlTemplate>
</Button.Template>
</Button>
im not sure what to write in my class, but what i found was something along the lines of this
private void BidderOne_Click(object sender, RoutedEventArgs e)
{
var selectedBidder = sender as Button;
// Button btn = new Button();
// btn = BidderOne;
ControlTemplate dt = BidderOne.Template;
Image btnImage = (Image)dt.TargetType = ;
var img = (Image)(selectedBidder.ContentTemplateRoot as StackPanel).Children[0];
var uri = new Uri("/Assetes/ClubsLogo.png", UriKind.Relative);
// var sri = Windows.UI.Xaml.Application.("Assetes/ClubsLogo.png", UriKind.Relative);
imgOn.UriSource=uri;
img.Source = imgOn;
}
It is not recommended to change the ControlTemplate of a Control at runtime. For these situations you should create a custom control.
I have written a simple ImageButton just so you can get the idea of creating what is needed for your problem.
Here is the code:
public sealed class ImageButton : Button
{
private Image _image;
public ImageButton()
{
this.DefaultStyleKey = typeof (Button);
_image = new Image();
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.Content = _image;
OnImage1SourceChanged(null, null);
}
public ImageSource Image1Source
{
get { return (ImageSource)GetValue(Image1SourceProperty); }
set { SetValue(Image1SourceProperty, value); }
}
public static readonly DependencyProperty Image1SourceProperty =
DependencyProperty.Register("Image1Source",
typeof (ImageSource),
typeof (ImageButton),
new PropertyMetadata(null, OnImage1SourceChangedCallback));
private static void OnImage1SourceChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var imageButton = d as ImageButton;
if (imageButton == null) return;
imageButton.OnImage1SourceChanged((ImageSource)e.OldValue, (ImageSource)e.NewValue);
}
private void OnImage1SourceChanged(ImageSource oldValue, ImageSource newValue)
{
if (_image != null)
{
_image.Source = Image1Source;
}
}
public ImageSource Image2Source
{
get { return (ImageSource)GetValue(Image2SourceProperty); }
set { SetValue(Image2SourceProperty, value); }
}
public static readonly DependencyProperty Image2SourceProperty =
DependencyProperty.Register("Image2Source",
typeof (ImageSource),
typeof (ImageButton),
new PropertyMetadata(null));
protected override void OnTapped(TappedRoutedEventArgs e)
{
base.OnTapped(e);
if (_image != null)
{
_image.Source = Image2Source;
}
}
}
and you use it like this:
<controls:ImageButton Width="60" Height="60" Image1Source="/Assets/Images/Chat/ic_comment_favorite_yellow.png" Image2Source="/Assets/Images/Flags/afghanistan.png"/>
Try this
EDITED
private void BidderOne_Click(object sender, RoutedEventArgs e) {
var selectedBidder = sender as Button;
// WRONG -> Image image = selectedBidder.Template.FindName("BidderOneImage", selectedBidder) as Image;
Image image = VisualTreeHelper.GetChild(selectedBidder, 0) as Image;
image.Source = new BitmapImage(new Uri("NEW IMAGE URI"));
}

Cant get selected listboxitem to show on my detail page

I have made and rss reader and have a listbox with all the feeds in it. When I select one item and want to see the whole article I only get the selectedindex number, 0,1,2 and so on.
Here is my code:
private void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null && listBox.SelectedItem != null)
{
NavigationService.Navigate(new Uri("/DetailsPage.xaml?feeditem=" + listBox.SelectedIndex, UriKind.Relative));
}
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string feeditem = "";
if (NavigationContext.QueryString.TryGetValue("feeditem", out feeditem))
{
this.textBlock1.Text = feeditem;
}
}
What am I missing here?

Resources