'Expected class, delegate, enum, interface,or struct' in XNA 4.0? - xna-4.0

Here's my code;
I've looked it up online, but still unable to fix it.
Please show me a fixed version of the code, thank you so much! I've been staring at the screen for half 'n' hour and still can't figure this out!
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D car1Texture;
Vector2 car1Position = new Vector2(200f, 100f);
Texture2D background;
Rectangle mainFrame;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//Change the resolution to 800x600
graphics.PreferredBackBufferWidth = 1000;
graphics.PreferredBackBufferHeight = 800;
graphics.ApplyChanges();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the background content.
background = Content.Load<Texture2D>("roadscan");
// Set the rectangle parameters
mainFrame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
spriteBatch = new SpriteBatch(GraphicsDevice);
car1Texture = Content.Load<Texture2D>("car1");
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState keyboard = Keyboard.GetState();
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
if (keyboard.IsKeyDown(Keys.Left) || gamePad.DPad.Left == ButtonState.Pressed)
{
ballPosition.X -= 3f;
}
if (keyboard.IsKeyDown(Keys.Right) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.X += 3f;
}
if (keyboard.IsKeyDown(Keys.Up) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y += 3f;
}
if (keyboard.IsKeyDown(Keys.Down) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y -= 3f;
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Draw the background.
// Start building the sprite.
spriteBatch.Begin();
// Draw the background.
spriteBatch.Draw(background, mainFrame, Color.White);
// End building the sprite.
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}

Remove the extra brace above the UnloadContent method
Right here:
// TODO: use this.Content to load your game content here
}<-------Delete this guy!!!
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}

You've got one to many closing curly braces.
protected override void LoadContent()
{
// snip
} //close method
// TODO: use this.Content to load your game content here
} //close class
You accidentally close the class half way through, just removing the curly brace will fix things. This is common when you haven't shrunk or removed the default comment blocks as they tend to get in the way after you've learnt what all the basic methods do.

Related

Change UIImage colors with Xamarin

I'm using Xamarin Forms and I have a UIImage (in a custom renderer) that I load from a file and that I use as a pattern.
The image is a 4x16 pixels with two 4x4 pixels black areas and a 4x8 transparent area:
I need to change the color of the black areas dinamically.
This is what I tried, without any success:
UIImage image = UIImage.FromFile("line_pattern.png");
image = image.ApplyTintColor(UIColor.Orange,UIImageRenderingMode.AlwaysTemplate);
The image is loaded correctly, but the color doesn't change. How can I do it?
Have a try to set the tintColor to imageView:
UIImageView imageView = new UIImageView();
UIImage image = UIImage.FromFile("line_pattern.png");
image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
image = image.ApplyTintColor(UIColor.Orange, UIImageRenderingMode.AlwaysTemplate);
imageView.Image = image;
imageView.TintColor = UIColor.Orange;
Setting the tint color works for PNGs with a single color.
However, we wanted to be able to change individual colors in UIImage objects loaded from JPGs or PNGs which may have more than one color. Our target images are icons or similar images that have a relatively limited number of distinct colors, and swapping one color for another seems like it should be simple, but none of the solutions we found online provided exactly what we were looking for.
So, to replace a color we created the following filter class derived from CIColorCube. We use this with images that have a relatively limited number of colors, but nothing prevents this from being used with more complex images. If you don't get the results you want, play with the CubeDimension and IndexPlusMinus properties to see how they affect the image.
This code is loosely based on the Apple Developer Chroma Key Filter Recipe example. The logic used there for setting the color map may be more appropriate for complex images like photos.
Finally, for anyone updating from Xamarin to MAUI, this code works on MAUI by simply changing the one nfloat reference to NFloat.
UPDATE: The sushihangover/ColorReplaceFilter.cs can also be used to replace colors. In fact, we had originally tried using the sushihangover code but had problems, so we created the color cube filter. Ultimately the problems we had with the sushihangover filter were our own doing; it works just fine once we figured that out. The performance of both the color cube filter and the sushihangover filter seem to be about the same, so either filter will do the job.
public class iOSReplaceColorFilter : CIColorCube
{
/// <summary>
/// The color to replace with NewColor. If not set, the color of all non-transparent
/// pixels in the image will be changed to NewColor.
/// </summary>
public CIColor OldColor { get; set; }
/// <summary>
/// The new color used to replace the old color.
/// </summary>
public CIColor NewColor { get; set; }
/// <summary>
/// An offset that is applied when calculating which color cube index values match
/// the old color. Set this to 1 to avoid interpolation of the new color when the
/// RGB color indices of the old color do not exactly resolve to integer values.
/// </summary>
public int IndexPlusMinus { get; set; } = 1;
/// <summary>
/// Default constructor. To use this, you must explictly set OldColor, NewColor, and
/// the CubeDimension, then call InitCube before getting the OutputImage.
/// </summary>
public iOSReplaceColorFilter()
{
}
/// <summary>
/// Create a replacement filter that uses the specified cube dimension for the color
/// cube map. The default dimension is 16, but cube dimensions as small as 2 can be
/// used. When replacing a color in an image with 2 or more distinct colors, the cube
/// dimension determines how close two colors' RGB values can be without introducing
/// interpolation effects.
/// </summary>
public iOSReplaceColorFilter(CIColor oldColor, CIColor newColor, int cubeDimension = 16)
{
OldColor = oldColor;
NewColor = newColor;
CubeDimension = cubeDimension;
InitCube();
}
/// <summary>
/// Create a replacement filter for replacing all non-transparent pixels in the image
/// with the specified color.
/// </summary>
public iOSReplaceColorFilter(CIColor newColor)
{
NewColor = newColor;
CubeDimension = 2;
InitCube();
}
/// <summary>
/// Build the color cube. This must be called before using OutputImage to get
/// the converted image.
/// </summary>
public virtual iOSReplaceColorFilter InitCube()
{
var dim = (int)CubeDimension;
var dimFactor = (float)(dim - 1);
var rangeChecker = new IndexRangeChecker(OldColor, dimFactor, IndexPlusMinus);
var offset = 0;
var cubeData = new float[dim * dim * dim * 4];
for (var b = 0; b < dim; ++b)
{
var blue = b / dimFactor;
for (var g = 0; g < dim; ++g)
{
var green = g / dimFactor;
for (var r = 0; r < dim; ++r)
{
var red = r / dimFactor;
if (NewColor != null && rangeChecker.Matches(r, g, b))
{
cubeData[offset++] = (float)NewColor.Red;
cubeData[offset++] = (float)NewColor.Green;
cubeData[offset++] = (float)NewColor.Blue;
}
else
{
cubeData[offset++] = red;
cubeData[offset++] = green;
cubeData[offset++] = blue;
}
cubeData[offset++] = 1.0f;
}
}
}
var byteArray = new byte[cubeData.Length * 4];
Buffer.BlockCopy(cubeData, 0, byteArray, 0, byteArray.Length);
var data = NSData.FromArray(byteArray);
CubeData = data;
return this;
}
/// <summary>
/// Checks to see if an r,g,b index set falls within the range of cube indices
/// that should be considered a "hit" on the target color. If the checker is
/// created with a null color, then all indices match.
/// </summary>
private class IndexRangeChecker
{
private IndexRange rRange;
private IndexRange gRange;
private IndexRange bRange;
public IndexRangeChecker(CIColor color, float dimFactor, int indexPlusMinus)
{
if (color != null)
{
rRange = new IndexRange(color.Red, dimFactor, indexPlusMinus);
gRange = new IndexRange(color.Green, dimFactor, indexPlusMinus);
bRange = new IndexRange(color.Blue, dimFactor, indexPlusMinus);
}
}
public bool Matches(int r, int g, int b)
{
if (rRange != null)
return rRange.Matches(r) && gRange.Matches(g) && bRange.Matches(b);
else
return true;
}
private class IndexRange
{
private int start;
private int end;
public IndexRange(nfloat colorValue, float dimFactor, int offset)
{
var indx = (int)Math.Round(dimFactor * colorValue);
start = indx - offset;
end = indx + offset;
}
public bool Matches(int indx) => start <= indx && indx <= end;
}
}
/// <summary>
/// Convenience function that creates and applies a iOSReplaceColorFilter to
/// an image and returns the resulting image.
/// </summary>
public static UIImage ReplaceColor(UIImage inputImage, CIColor oldColor, CIColor newColor)
{
var filter = new iOSReplaceColorFilter(oldColor, newColor);
filter.InputImage = new CIImage(inputImage);
var outputImage = iOSColorCubeUtil.RenderFilteredImage(filter.OutputImage, inputImage);
return outputImage;
}
}
public class iOSColorCubeUtil
{
/// <summary>
/// Render an image after all filters have been applied. If you have more than one
/// filter, the output of each should be passed to the next filter, and only the final
/// filter result should be passed to this function.
///
/// For example, to apply a sepia tone filter and then an invert filter, do this:
///
/// var sepiaFilter = new CISepiaTone { Intensity = 0.8f, InputImage = myImage };
/// var invertFilter = new CIColorInvert { InputImage = sepiaFilter.OutputImage };
/// var finalImage = RenderFilteredImage(invertFilter.OutputImage);
///
/// The originalImage is needed as a argument in order to render the image using the
/// same scale factor and orientation as the original image.
/// </summary>
public static UIImage RenderFilteredImage(CIImage filteredImage, UIImage originalImage)
{
// The ColorSpace MUST be set in order for the CIColorCube mapping to work. If
// the color space isn't set, CIColorCube-based color swapping only worked for
// target colors whose RGB color values were all either 0x00 or 0xFF (e.g. #000000,
// #FFFFFF, #FF0000, #FF00FF, etc.)
var rgbColorSpace = CGColorSpace.CreateDeviceRGB();
var options = new CIContextOptions
{
WorkingColorSpace = rgbColorSpace,
OutputColorSpace = rgbColorSpace
};
var context = CIContext.FromOptions(options);
var cgImage = context.CreateCGImage(filteredImage, filteredImage.Extent);
var fixedImage = UIImage.FromImage(cgImage, originalImage.CurrentScale, originalImage.Orientation);
return fixedImage;
}
}

Getting poor quality picture in Windows UWP if taken immediately after start

Getting poor quality picture in Windows UWP if taken immediately after starting preview. TakePhotoAsync() is called in StartPreviewAsync() task then part. Consistently getting poor quality pictures. How to get good quality picture immediately after starting preview?. Code is based on CameraStarterKit.
/// <summary>
/// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
/// </summary>
/// <returns></returns>
task<void> MainPage::InitializeCameraAsync()
{
DBOUT(__func__);
WriteLine("InitializeCameraAsync");
// Get available devices for capturing pictures
return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Back)
.then([this](DeviceInformation^ camera)
{
if (camera == nullptr)
{
WriteLine("No camera device found!");
return;
}
// Figure out where the camera is located
if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
{
// No information on the location of the camera, assume it's an external camera, not integrated on the device
_externalCamera = true;
}
else
{
// Camera is fixed on the device
_externalCamera = false;
// Only mirror the preview if the camera is on the front panel
_mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
}
_mediaCapture = ref new Capture::MediaCapture();
// Register for a notification when video recording has reached the maximum time and when something goes wrong
_recordLimitationExceededEventToken =
_mediaCapture->RecordLimitationExceeded += ref new Capture::RecordLimitationExceededEventHandler(this, &MainPage::MediaCapture_RecordLimitationExceeded);
_mediaCaptureFailedEventToken =
_mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
auto settings = ref new Capture::MediaCaptureInitializationSettings();
settings->VideoDeviceId = camera->Id;
settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
// Initialize media capture and start the preview
create_task(_mediaCapture->InitializeAsync(settings))
.then([this]()
{
_isInitialized = true;
return StartPreviewAsync()
.then([this]()
{
UpdateCaptureControls();
});
}).then([this](task<void> previousTask)
{
try
{
previousTask.get();
}
catch (AccessDeniedException^)
{
WriteLine("The app was denied access to the camera");
}
});
});
}
/// <summary>
/// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
/// </summary>
/// <returns></returns>
task<void> MainPage::StartPreviewAsync()
{
DBOUT(__func__);
// Prevent the device from sleeping while the preview is running
_displayRequest->RequestActive();
// Set the preview source in the UI and mirror it if necessary
PreviewControl->Source = _mediaCapture.Get();
PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
// Start the preview
return create_task(_mediaCapture->StartPreviewAsync())
.then([this](task<void> previousTask)
{
_isPreviewing = true;
FN_TRACE("CameraStreamState::Streaming %d\n", _mediaCapture->CameraStreamState);
TakePhotoAsync();
// Only need to update the orientation if the camera is mounted on the device
if (!_externalCamera)
{
return SetPreviewRotationAsync();
}
// Not external, just return the previous task
return previousTask;
});
}
/// <summary>
/// Takes a photo to a StorageFile and adds rotation metadata to it
/// </summary>
/// <returns></returns>
task<void> MainPage::TakePhotoAsync()
{
DBOUT(__func__);
// While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
VideoButton->IsEnabled = _mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported;
// Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
VideoButton->Opacity = VideoButton->IsEnabled ? 1 : 0;
auto inputStream = ref new Streams::InMemoryRandomAccessStream();
// Take the picture
WriteLine("Taking photo...");
return create_task(_mediaCapture->CapturePhotoToStreamAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg(), inputStream))
.then([this, inputStream]()
{
return create_task(_captureFolder->CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption::GenerateUniqueName));
}).then([this, inputStream](StorageFile^ file)
{
WriteLine("Photo taken! Saving to " + file->Path);
// Done taking a photo, so re-enable the button
VideoButton->IsEnabled = true;
VideoButton->Opacity = 1;
auto photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
return ReencodeAndSavePhotoAsync(inputStream, file, photoOrientation);
}).then([this](task<void> previousTask)
{
try
{
previousTask.get();
}
catch (Exception^ ex)
{
// File I/O errors are reported as exceptions
WriteException(ex);
}
});
}

GoBack() to previous page UWP

I launch a page on UWP thanks to PageRenderer, this page allows take picture and I want go back when user take a pciture.
My problem is when I go back with hardware button I have no problem but with function goback doesn't work.
This is my code :
var frame = Window.Current.Content as Frame;
if (frame != null && frame.CanGoBack)
{
frame.GoBack();
}
CanGoBack return false.
So you have some idea
Thanks
You need to hook into the back button pressed and then force the navigation back
public PageContainer()
{
this.InitializeComponent();
SystemNavigationManager.GetForCurrentView().BackRequested += PageContainer_BackRequested;
}
/// <summary>
/// Handles when the user presses the back button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PageContainer_BackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null){
return;
}
// Navigate back if possible, and if the event has not
// already been handled .
if (rootFrame.CanGoBack && e.Handled == false)
{
e.Handled = true;
rootFrame.GoBack();
}
}
This example is an adaptation of the example provided on the MSDN website
You have to use the BackPressed Event.
public Test()
{
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
private void Test_BackPressed(object sender, BackPressedEventArgs e)
{
if (this.Layer.CanGoBack)
{
e.Handled = true;
this.Layer.GoBack();
}
}

Changes to Pushpin.Location Inside ObservableCollection Don't Affect The Pushpin Until Map Is Redrawn

First question here, so far I've received great help just reading the answers. This is something I couldn't find any answers on though. So here comes...
We have a Bing Maps map whose MapItemsControl is bound to ObservableCollection<Pushpin> Property. When adding/removing items to the collection the map gets updated correctly.
Now my question is this: how to update/bind the location of a Pushpin inside the collection so it is reflected on the map without redrawing the map by moving/zooming?
Here is the Map.xaml:
<phone:PhoneApplication ...
DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
<maps:Map ...>
<maps:MapItemsControl ItemsSource="{Binding MapItems}"/>
</maps:Map>
</phone:PhoneApplication>
MainViewModel.xaml:
#region MapItems
#region MapItems Property
/// <summary>
/// The <see cref="MapItems" /> property's name.
/// </summary>
public const string MapItemsPropertyName = "MapItems";
private ObservableCollection<Pushpin> _MapItems =
new ObservableCollection<Pushpin>();
/// <summary>
/// Sets and gets the MapItems property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<Pushpin> MapItems
{
get
{
return _MapItems;
}
set
{
if (_MapItems == value)
{
return;
}
_MapItems = value;
RaisePropertyChanged(MapItemsPropertyName);
}
}
#endregion
#region OwnLocation
private Pushpin OwnLocation;
private void InitializeOwnLocation()
{
OwnLocation = new Pushpin()
{
Style = App.Current.Resources["OwnLocationStyle"] as Style
};
Binding b = new Binding {
Path = new PropertyPath("LastKnownLocation")
};
OwnLocation.SetBinding(Pushpin.LocationDependencyProperty, b);
MapItems.Add(OwnLocation);
}
#endregion
...
#endregion
LastKnownLocation is being set in the PositionChanged of the GeoCoordinateWatcher
Update (30.5.2012 20.35). Implementation of LastKnownLocation property.
/// <summary>
/// The <see cref="LastKnownLocation" /> property's name.
/// </summary>
public const string LastKnownLocationPropertyName = "LastKnownLocation";
private GeoCoordinate _LastKnownLocation;
/// <summary>
/// Sets and gets the LastKnownLocation property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public GeoCoordinate LastKnownLocation
{
get
{
return _LastKnownLocation;
}
private set
{
if (_LastKnownLocation == value)
{
return;
}
var oldValue = _LastKnownLocation;
_LastKnownLocation = value;
Settings["LastKnownLocation"] = _LastKnownLocation;
RaisePropertyChanged(LastKnownLocationPropertyName, oldValue, value, true);
}
}
x:Name= myMap on map Control
When you want to rebind your map pins
set
myMap.Children.Clear()
then re-add your Pins.
you can notify your data change
As I commented earlier after long Googling I finally came to a workaround that doesn't seem to be available anymore. The trick is to call SetView on the map view after changing Pushpin.Location.

Watin AddDialogHandler method throwing null reference exception in FF

I'm trying to add ConfirmDialogHandler to dialog handler and i get NullReferenceException.
This happens on FF 3.6 with latest watin version, the same code works on IE7 and 8.
ConfirmDialogHandler confirmDialogHandler = new ConfirmDialogHandler();
browser.AddDialogHandler(confirmDialogHandler); // --> exception here
Any ideas?
Old Solution
Found the problem.
The DialogWatcher was not initialized when FF session was created added this line to watin code:
private void CreateFireFoxInstance(string url)
{
Logger.LogAction("Creating FireFox instance");
UtilityClass.MoveMousePoinerToTopLeft(Settings.AutoMoveMousePointerToTopLeft);
var clientPort = GetClientPort();
clientPort.Connect(url);
_ffBrowser = new FFBrowser(clientPort);
StartDialogWatcher(); // <-- Added line
WaitForComplete();
}
Please Note - This is the workaround
The provided solution didn't worked
This is my workaround:
I used AutoIt dll and handled the popups by my self, code sample:
using AutoItX3Lib;
public static void RunAutomaticEnterCommand(Session session)
{
var autoIt = GetPopupHandle();
autoIt.Send("{ENTER}");
Thread.Sleep(1000);
}
/// <summary>
/// Cancel the popup
/// For FF
/// </summary>
/// <param name="session"></param>
public static void RunAutomaticCancelCommand(Session session)
{
var autoIt = GetPopupHandle();
autoIt.Send("{TAB}");
autoIt.Send("{ENTER}");
Thread.Sleep(1000);
}
/// <summary>
/// Return the autoit popup handler
/// AutoIt is a script language, we using it to handle the firefox popups
/// </summary>
/// <returns></returns>
private static AutoItX3Class GetPopupHandle()
{
var autoIt = new AutoItX3Class();
autoIt.AutoItSetOption("WinTitleMatchMode", 2);
const string partialTitle = "The page at"; //the popup in Firefox starts with this text
autoIt.WinWait(partialTitle, "", 30);
string fullTitle = autoIt.WinGetTitle(partialTitle); //Get the whole popup title
autoIt.WinActivate(fullTitle); //Get focis to the popup
if (autoIt.WinWaitActive(fullTitle, "", 20) == 0)
{
reporter.Report("Failed to get the FireFox popup handle", false);
return autoIt;
}
return autoIt;
}

Resources