Using the Windows Phone 7 camera in an XNA game
This came up in an AppHub forums post and it seemed to help the person out so I figured I’d post it here for posterity (and the fact that I haven’t posted here in ages
)
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; using Microsoft.Phone.Tasks; namespace Camera_Test { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; bool _cameraError = false; SpriteFont _font; Vector2 _errorLocation; Texture2D _texture; Rectangle _rect; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; TargetElapsedTime = TimeSpan.FromTicks(333333); InactiveSleepTime = TimeSpan.FromSeconds(1); TouchPanel.EnabledGestures = GestureType.Tap; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); _font = Content.Load<SpriteFont>("font"); _errorLocation = new Vector2(25, 25); } protected override void Update(GameTime gameTime) { GamePadState state = GamePad.GetState(PlayerIndex.One); if (state.Buttons.Back == ButtonState.Pressed) this.Exit(); if (TouchPanel.IsGestureAvailable) { if (TouchPanel.ReadGesture().GestureType == GestureType.Tap) { CameraCaptureTask cameraCaptureTask = new CameraCaptureTask(); cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed); try { cameraCaptureTask.Show(); } catch (InvalidOperationException ex) { _cameraError = true; } } } base.Update(gameTime); } void cameraCaptureTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { _texture = Texture2D.FromStream(graphics.GraphicsDevice, e.ChosenPhoto); _rect = new Rectangle(50, 50, _texture.Width, _texture.Height); } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); if(_texture != null) spriteBatch.Draw(_texture, _rect, Color.White); if (_cameraError) spriteBatch.DrawString(_font, "Camera error", _errorLocation, Color.White); base.Draw(gameTime); } } }
Tap the screen to allow a photo to be taken. That photo will be stuffed into a Texture2D object and rendered in the game.
Note: you’ll need to add a SpriteFont to the Content project called “font.spritefont”.
While the person that asked the question says this worked for him, I haven’t tested it.