Windows Phone From Scratch #24
On January 24 we created an application that launched the contact list and returned the phone number of the selected contact. In that posting I reviewed, briefly, the difference between Launchers and Choosers. This posting builds on that work.
Today we will use the Chooser for the Camera, which will bring up the camera and then return the location of the image taken.
To begin, create a new Windows Phone application, called Camera Test.
On the main page place a Button and an Image control,
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="101*" /> <RowDefinition Height="506*" /> </Grid.RowDefinitions> <Button x:Name="Photo" Content="Photo" Height="72" HorizontalAlignment="Left" Margin="154,29,0,0" VerticalAlignment="Top" Width="160" /> <Image Grid.Row="1" Height="253" HorizontalAlignment="Left" Margin="84,68,0,0" Name="Image1" Stretch="Fill" VerticalAlignment="Top" Width="303" /> </Grid>
Following the same pattern as we saw with the Contacts chooser, declare the camera chooser as a member variable of the class,
using System; using System.Windows; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; using System.Windows.Media.Imaging; namespace CameraTest { public partial class MainPage : PhoneApplicationPage { CameraCaptureTask _cameraCapture = new CameraCaptureTask();
Wire up the click event handler to call Show on the CameraCaptureTask and wire up an event handler for the callback to handle the picture that was taken,
public MainPage() { InitializeComponent(); _cameraCapture.Completed += new EventHandler<PhotoResult>( _cameraCapture_Completed ); Photo.Click += new RoutedEventHandler( Photo_Click ); }
Finally, in the callback, you’ll obtain the fileName that contains the image and use that to create a new BitMapImage which can serve as the Source for your Image control,
void _cameraCapture_Completed( object sender, PhotoResult e ) { if ( e.TaskResult == TaskResult.OK ) { Image1.Source = new BitmapImage( new Uri( e.OriginalFileName ) ); } }
The emulator provides a simulated image to capture (a small moving rectangle against a white background) and a simulated button to snap to capture the image when the rectangle is where you want it.
Awesome, I’ll try this out when I get home. Thanks for the tutorial.