Usuário com melhor resposta
Alternar câmera frontal com a traseira

Pergunta
-
Eu sou iniciante aqui e pra começar eu fiz uma câmera, seguindo os passos do How to create a base camera app for Windows Phone, só que lá não ensina como alternar entre a camera frontal e a traseira.Tente varias coisas e ainda não consegui, pois o local que seleciona a ela é dentro do onNavigatedTo, e eu não sei como chamar ele e modifica-lo. Esse é o meu código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using CameraApp1.Resources;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace CameraApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Variables
private int savedCounter = 0, type = 1;
String camera;
PhotoCamera cam;
MediaLibrary library = new MediaLibrary();
// Holds current flash mode.
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
//Code for initialization, capture completed, image availability events; also setting the source for the viewfinder.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
// Check to see if the camera is available on the phone.
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
{
cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
// Initialize the camera, when available.
/* if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing))
{
// Use front-facing camera if available.
cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);
}
else
{
// Otherwise, use standard camera on back of phone.
cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
} */
// Event is fired when the PhotoCamera object has been initialized.
cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
// Event is fired when the capture sequence is complete.
cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_CaptureCompleted);
// Event is fired when the capture sequence is complete and an image is available.
cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
// Event is fired when the capture sequence is complete and a thumbnail image is available.
cam.CaptureThumbnailAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureThumbnailAvailable);
//Set the VideoBrush source to the camera.
viewfinderBrush.SetSource(cam);
// The event is fired when the shutter button receives a half press.
CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
// The event is fired when the shutter button receives a full press.
CameraButtons.ShutterKeyPressed += OnButtonFullPress;
// The event is fired when the shutter button is released.
CameraButtons.ShutterKeyReleased += OnButtonRelease;
// The event is fired when the viewfinder is tapped (for focus).
viewfinderCanvas.Tap += new EventHandler<GestureEventArgs>(focus_Tapped);
cam.AutoFocusCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_AutoFocusCompleted);
}
else
{
// The camera is not supported on the phone.
this.Dispatcher.BeginInvoke(delegate()
{
// Write message.
txtDebug.Text = "A Camera is not available on this phone.";
});
// Disable UI.
ShutterButton.IsEnabled = false;
FlashButton.IsEnabled = false;
AFButton.IsEnabled = false;
}
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (cam != null)
{
// Dispose camera to minimize power consumption and to expedite shutdown.
cam.Dispose();
// Release memory, ensure garbage collection.
cam.Initialized -= cam_Initialized;
cam.CaptureCompleted -= cam_CaptureCompleted;
cam.CaptureImageAvailable -= cam_CaptureImageAvailable;
cam.CaptureThumbnailAvailable -= cam_CaptureThumbnailAvailable;
CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;
CameraButtons.ShutterKeyPressed -= OnButtonFullPress;
CameraButtons.ShutterKeyReleased -= OnButtonRelease;
cam.AutoFocusCompleted -= cam_AutoFocusCompleted;
}
}
// Provide touch focus in the viewfinder.
void focus_Tapped(object sender, GestureEventArgs e)
{
if (cam != null)
{
if (cam.IsFocusAtPointSupported == true)
{
try
{
// Determine the location of the tap.
Point tapLocation = e.GetPosition(viewfinderCanvas);
// Position the focus brackets with the estimated offsets.
focusBrackets.SetValue(Canvas.LeftProperty, tapLocation.X - 30);
focusBrackets.SetValue(Canvas.TopProperty, tapLocation.Y - 28);
// Determine the focus point.
double focusXPercentage = tapLocation.X / viewfinderCanvas.Width;
double focusYPercentage = tapLocation.Y / viewfinderCanvas.Height;
// Show the focus brackets and focus at point.
focusBrackets.Visibility = Visibility.Visible;
cam.FocusAtPoint(focusXPercentage, focusYPercentage);
// Write a message to the UI.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = String.Format("Camera focusing at point: {0:N2} , {1:N2}", focusXPercentage, focusYPercentage);
});
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
// Write a message to the UI.
txtDebug.Text = focusError.Message;
// Hide focus brackets.
focusBrackets.Visibility = Visibility.Collapsed;
});
}
}
else
{
// Write a message to the UI.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Camera does not support FocusAtPoint().";
// Hide the focus brackets.
focusBrackets.Visibility = Visibility.Collapsed;
});
}
}
}
// Provide autofocus in the viewfinder.
private void focus_Clicked(object sender, System.Windows.RoutedEventArgs e)
{
if (cam.IsFocusSupported == true)
{
//Focus when a capture is not in progress.
try
{
cam.Focus();
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
else
{
// Write message to UI.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Camera does not support programmable autofocus.";
});
}
}
void cam_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
// Write message to UI.
txtDebug.Text = "Autofocus has completed.";
});
}
// Provide auto-focus with a half button press using the hardware shutter button.
private void OnButtonHalfPress(object sender, EventArgs e)
{
if (cam != null)
{
// Focus when a capture is not in progress.
try
{
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Half Button Press: Auto Focus";
});
cam.Focus();
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
}
// Capture the image with a full button press using the hardware shutter button.
private void OnButtonFullPress(object sender, EventArgs e)
{
if (cam != null)
{
cam.CaptureImage();
}
}
// Cancel the focus if the half button press is released using the hardware shutter button.
private void OnButtonRelease(object sender, EventArgs e)
{
if (cam != null)
{
cam.CancelFocus();
}
}
// Update the UI if initialization succeeds.
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
if (e.Succeeded)
{
this.Dispatcher.BeginInvoke(delegate()
{
// Write message.
txtDebug.Text = "Camera initialized.";
// Set flash button text.
if (camera == "Front")
FlashButton.Content = "Off";
else
FlashButton.Content = cam.FlashMode.ToString();
});
}
}
// Ensure that the viewfinder is upright in LandscapeRight.
protected override void OnOrientationChanged(OrientationChangedEventArgs e)
{
if (cam != null)
{
// LandscapeRight rotation when camera is on back of phone.
int landscapeRightRotation = 180;
// Change LandscapeRight rotation for front-facing camera.
if (cam.CameraType == CameraType.FrontFacing) landscapeRightRotation = -180;
// Rotate video brush from camera.
if (e.Orientation == PageOrientation.LandscapeRight)
{
// Rotate for LandscapeRight orientation.
viewfinderBrush.RelativeTransform =
new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = landscapeRightRotation };
}
else
{
// Rotate for standard landscape orientation.
viewfinderBrush.RelativeTransform =
new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
}
}
base.OnOrientationChanged(e);
}
private void ShutterButton_Click(object sender, RoutedEventArgs e)
{
if (cam != null)
{
try
{
// Start image capture.
cam.CaptureImage();
}
catch (Exception ex)
{
this.Dispatcher.BeginInvoke(delegate()
{
// Cannot capture an image until the previous capture has completed.
txtDebug.Text = ex.Message;
});
}
}
}
void cam_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
// Increments the savedCounter variable used for generating JPEG file names.
savedCounter++;
}
// Informs when full resolution photo has been taken, saves to local media library and the local folder.
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = savedCounter + ".jpg";
try
{ // Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving photo.";
});
// Save photo to the media library camera roll.
library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Photo has been saved to camera roll.";
});
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save photo as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to the local folder.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Photo has been saved to the local folder.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
// Informs when thumbnail photo has been taken, saves to the local folder
// User will select this image in the Photos Hub to bring up the full-resolution.
public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)
{
string fileName = savedCounter + "_th.jpg";
try
{
// Write message to UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving thumbnail.";
});
// Save thumbnail as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the thumbnail to the local folder.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Thumbnail has been saved to the local folder.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
// Activate a flash mode.
// Cycle through flash mode options when the flash button is pressed.
private void changeFlash_Clicked(object sender, RoutedEventArgs e)
{
if (camera == "Front")
FlashButton.Content = "Off";
else
{
switch (cam.FlashMode)
{
case FlashMode.Off:
if (cam.IsFlashModeSupported(FlashMode.On))
{
// Specify that flash should be used.
cam.FlashMode = FlashMode.On;
FlashButton.Content = "On";
}
break;
case FlashMode.On:
if (cam.IsFlashModeSupported(FlashMode.RedEyeReduction))
{
// Specify that the red-eye reduction flash should be used.
cam.FlashMode = FlashMode.RedEyeReduction;
FlashButton.Content = "RER";
}
else if (cam.IsFlashModeSupported(FlashMode.Auto))
{
// If red-eye reduction is not supported, specify automatic mode.
cam.FlashMode = FlashMode.Auto;
FlashButton.Content = "Auto";
}
else
{
// If automatic is not supported, specify that no flash should be used.
cam.FlashMode = FlashMode.Off;
FlashButton.Content = "Off";
}
break;
case FlashMode.RedEyeReduction:
if (cam.IsFlashModeSupported(FlashMode.Auto))
{
// Specify that the flash should be used in the automatic mode.
cam.FlashMode = FlashMode.Auto;
FlashButton.Content = "Auto";
}
else
{
// If automatic is not supported, specify that no flash should be used.
cam.FlashMode = FlashMode.Off;
FlashButton.Content = "Off";
}
break;
case FlashMode.Auto:
if (cam.IsFlashModeSupported(FlashMode.Off))
{
// Specify that no flash should be used.
cam.FlashMode = FlashMode.Off;
FlashButton.Content = "Off";
}
break;
}
}
}
public object sender { get; set; }
}
}- Editado Guto Acorsi sexta-feira, 10 de abril de 2015 16:41
sexta-feira, 10 de abril de 2015 14:21
Respostas
-
Olá Guto,
O código em How to create a base camera app for Windows Phoneassume que a aplicação pode ser executada em diferentes hardwares e por isso verifica se o hardware em questão tem câmera de um lado ou do outro. Esta verificação é feita no momento que a página é carregada usando o evento “OnNavigatedTo” (O “OnNavigatedTo” é chamado quando a página é carregada e torna-se corrente em um Frame do pai) para evitar qualquer erro com o aplicativo e ser transparente para o usuário.
No seu caso, pelo que entendi, você gostaria de ter um dispositivo para fazer o “switch” de uma câmera para outra. Existem várias maneiras de implementar isso. Você poderia criar um botão e fazer o “switch” dentro do evento “OnClick”. Ou ao mudar para uma nova página, ai a implementação seria parecida, dentro do evento “OnNavigatedTo”.
Boa sorte!
Veiga
- Sugerido como Resposta Eduardo.Romero segunda-feira, 13 de abril de 2015 12:07
- Marcado como Resposta Eduardo.Romero segunda-feira, 13 de abril de 2015 12:07
sexta-feira, 10 de abril de 2015 19:06
Todas as Respostas
-
Olá Guto,
O código em How to create a base camera app for Windows Phoneassume que a aplicação pode ser executada em diferentes hardwares e por isso verifica se o hardware em questão tem câmera de um lado ou do outro. Esta verificação é feita no momento que a página é carregada usando o evento “OnNavigatedTo” (O “OnNavigatedTo” é chamado quando a página é carregada e torna-se corrente em um Frame do pai) para evitar qualquer erro com o aplicativo e ser transparente para o usuário.
No seu caso, pelo que entendi, você gostaria de ter um dispositivo para fazer o “switch” de uma câmera para outra. Existem várias maneiras de implementar isso. Você poderia criar um botão e fazer o “switch” dentro do evento “OnClick”. Ou ao mudar para uma nova página, ai a implementação seria parecida, dentro do evento “OnNavigatedTo”.
Boa sorte!
Veiga
- Sugerido como Resposta Eduardo.Romero segunda-feira, 13 de abril de 2015 12:07
- Marcado como Resposta Eduardo.Romero segunda-feira, 13 de abril de 2015 12:07
sexta-feira, 10 de abril de 2015 19:06 -
Muito obrigado Eduardo, eu utilizei uma nova página e dentro do "OnNavigatedTo" e funcionou certinho.segunda-feira, 13 de abril de 2015 12:38