I have the following code in C#. A function by which I want to highlight one of the nine images at random. The code is as follows,
public void randomize(object sender, MouseButtonEventArgs e)
{
String img = "image";
int random = RandomNumber(10, 18); //Generate Random Number
score.Content = random;
img += random; //append generated number to "image"
//Call function to highlight behind image
ToGold(random);
}
I tried to make the function call ToGold(random) to be able to dynamically refer to one of the images on XAML. But I was not able to make the code work as I intended. So I took a brute force approach as below,
public void ToGold(int Img)
{
Uri gold = new Uri("/Start;component/Images/gold1.png", UriKind.Relative); //Set Uri path of gold image
ImageSource ImgSrc = new BitmapImage(gold); //Define ImageSource and assign
switch(Img)
{
case 10:
{
image10.Source = ImgSrc;
break;
}
case 11:
{
image11.Source = ImgSrc;
break;
}
case 12:
{
image12.Source = ImgSrc;
break;
}
case 13:
{
image13.Source = ImgSrc;
break;
}
case 14:
{
image14.Source = ImgSrc;
break;
}
case 15:
{
image15.Source = ImgSrc;
break;
}
case 16:
{
image16.Source = ImgSrc;
break;
}
case 17:
{
image17.Source = ImgSrc;
break;
}
case 18:
{
image18.Source = ImgSrc;
break;
}
}
}
So my question is how do I make the code efficient by making it dynamic? Can anyone please help me?
NOTE: I have just started studying WPF. So please bear with me.
You can use the FindName method on the window to find an element by its name.
Or you could create an array containing your images in order, i.e. { image0, image1, image2, image3, ... } and then access that array with a random index.
Related
I want to add to this game: https://www.mooict.com/wpf-c-tutorial-create-a-fun-balloon-popping-game-in-visual-studio/
A function ColorKeyIsDown() that is activated when some of keys: Y,R,B,G,O are pressed.
So, if any of these keys is pressed, a specific balloon will be removed from the canvas.
I made 5 possible tags for every newBalloon that is made,
because ballonSkins integer value is from 1-5, every number declares a different background of the newBallon.
In ColorKeyIsDown() I want to identify the balloons by their tags,
But it does not work.
How can I identify each different balloon(yellow/red/blue balloon)?
Can I identify the balloon by it's background?
*In XAML:
<Canvas Name="MyCanvas" Focusable="True" MouseLeftButtonDown="popBalloons" Background="White" KeyDown="ColorKeyIsDown">
<Label Name="scoreLabel" FontSize="24" Content="Score: 0" Foreground="black" FontWeight="ExtraBold" Canvas.Top="527" />
</Canvas>
*In C# Code:
private void ColorKeyIsDown(object sender, KeyEventArgs e)
{
if (gameisactive)
{
foreach(var x in MyCanvas.Children.OfType<Rectangle>())
{
switch (e.Key)
{
case Key.Y:
if ((string)x.Tag == 3.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.R:
if ((string)x.Tag == 1.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.B:
if ((string)x.Tag == 5.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.G:
if ((string)x.Tag == 4.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.O:
if ((string)x.Tag == 2.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
}
}
}
}
*In C#- in gameEngine() function:
// check which skin number is selected and change them to that number
switch (balloonSkins)
{
case 1:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon1.png"));
break;
case 2:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon2.png"));
break;
case 3:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon3.png"));
break;
case 4:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon4.png"));
break;
case 5:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon5.png"));
break;
}
// make a new rectangle called new balloon
// inside this it has a tag called bloon, height 70 pixels and width 50 pixels and balloon image as the background
Rectangle newBalloon = new Rectangle
{
Tag = balloonSkins.ToString(),
Height = 70,
Width = 50,
Fill=balloonImage
};
Someone wrote that instead of doing the KeyDown event in Canvas,
to do it in the window browser. solution: onkeydown event not working on canvas?
*I changed it, and it works!
Im using the following code to fix the orientation of image taking into account the EXIF Orientation Tag
static void FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
srce.RotateFlip( RotateFlipType.Rotate180FlipX);
break;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
}
}
This code removes the EXIF Orientation Tag properly.
And saving the image works is i simply use img.save
But the app provides user the ability to select the format of the image.For that i use the following code
private void saveJpeg(string path, Bitmap img, long quality)
{
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
ImageCodecInfo Codec = this.getEncoderInfo(imgformat);
if (Codec == null)
return;
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path + ext, Codec, encoderParams);
}
public string getimgext(string ccodec)
{
if (ccodec.Equals("image/png"))
{
return ".png";
}
else if (ccodec.Equals("image/jpeg"))
{
return ".jpg";
}
else if (ccodec.Equals("image/tiff"))
{
return ".tif";
}
else if (ccodec.Equals("image/bmp"))
{
return ".bmp";
}
else if (ccodec.Equals("image/gif"))
{
return ".gif";
}
else
{
return null;
}
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
When i save the image with SaveJpeg the image gets saved with wrong orientation.What im i doing wrong? Please help.
UPDATE:
I have modified the method so that i dont need to create a new instance of the bitmap as the loop processes many files.But this does not work unless i create a new instance of the bitmap.This process consumes an additional of 10+ seconds of the processing time when compared to the old version.
Im using the code like this
image = (Bitmap)FixImageOrientation(Bitmap.FromFile(path));
Image FixImageOrientation(Image srce)
{
const int ExifOrientationId = 0x112;
// Read orientation tag
if (!srce.PropertyIdList.Contains(ExifOrientationId)) return srce;
var prop = srce.GetPropertyItem(ExifOrientationId);
var orient = BitConverter.ToInt16(prop.Value, 0);
// Force value to 1
prop.Value = BitConverter.GetBytes((short)1);
srce.SetPropertyItem(prop);
// Rotate/flip image according to <orient>
switch (orient)
{
case 1:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
case 2:
srce.RotateFlip(RotateFlipType.RotateNoneFlipX);
return srce;
case 3:
srce.RotateFlip(RotateFlipType.Rotate180FlipNone);
return srce;
case 4:
srce.RotateFlip(RotateFlipType.Rotate180FlipX);
return srce;
case 5:
srce.RotateFlip(RotateFlipType.Rotate90FlipX);
return srce;
case 6:
srce.RotateFlip(RotateFlipType.Rotate90FlipNone);
return srce;
case 7:
srce.RotateFlip(RotateFlipType.Rotate270FlipX);
return srce;
case 8:
srce.RotateFlip(RotateFlipType.Rotate270FlipNone);
return srce;
default:
srce.RotateFlip(RotateFlipType.RotateNoneFlipNone);
return srce;
}
}
In one method you have argument of type Image but in other Bitmap. So I'm guessing that you convert source JPEG image to Bitmap before call FixImageOrientation.
This will work:
var jpeg = Image.FromFile("original.jpg");
FixImageOrientation(jpeg);
var bitmap = new Bitmap(jpeg);
saveJpeg("new",bitmap,1);
This won't:
var jpeg = Image.FromFile("original.jpg");
var bitmap = new Bitmap(jpeg);
FixImageOrientation(bitmap);
saveJpeg("new", bitmap, 1);
I have made a loading screen (splash screen) just like the old C64.
I have used a series of picture boxes and just change the coloured image using a timer and a case statement.
switch (a)
{
case 1:
pictureBox1.Image = Properties.Resources.image1;
pictureBox8.Image = Properties.Resources.image1;
pictureBox10.Image = Properties.Resources.image1;
pictureBox2.Image = Properties.Resources.image1;
pictureBox11.Image = Properties.Resources.image1;
pictureBox9.Image = Properties.Resources.image1;
break;
case 2:
pictureBox1.Image = Properties.Resources.image2;
pictureBox8.Image = Properties.Resources.image2;
pictureBox10.Image = Properties.Resources.image2;
break;
case 3:
pictureBox1.Image = Properties.Resources.image3;
pictureBox8.Image = Properties.Resources.image3;
pictureBox10.Image = Properties.Resources.image3;
break;
case 4:
pictureBox1.Image = Properties.Resources.image4;
pictureBox8.Image = Properties.Resources.image4;
break;
case 5:
pictureBox1.Image = Properties.Resources.image5;
pictureBox8.Image = Properties.Resources.image5;
break;
case 6:
pictureBox1.Image = Properties.Resources.image6;
pictureBox8.Image = Properties.Resources.image6;
break;
case 7:
pictureBox1.Image = Properties.Resources.image7;
pictureBox8.Image = Properties.Resources.image7;
break;
case 8:
pictureBox1.Image = Properties.Resources.image8;
pictureBox8.Image = Properties.Resources.image8;
break;
}
its a bit nasty looking, how could I improve my code?
You could have a look at the Iterator design pattern. You could create a class that represents a single stage, that class would have properties for each of the picture boxes and you would set the value of those properties to the relevant item in your resources file.
You then create instances of that object for each loading stage, put them in a collection and write an iterator to loop that collection.
There are a two things I'd improve:
Store your images in an array, so you don't have to repeat case X/imageX every time.
Handle the common stuff first, then concentrate on the special cases.
You can declare the array in your form as a "fake" constant, since it won't change:
private readonly static Image[] myImages = new[] {
Properties.Resources.image1,
Properties.Resources.image2,
Properties.Resources.image3,
Properties.Resources.image4,
Properties.Resources.image5,
Properties.Resources.image6,
Properties.Resources.image7,
Properties.Resources.image8
}
and then use the following code in your Timer hander:
Image image = myImages[a-1];
pictureBox1.Image = image;
pictureBox8.Image = image;
// special cases
if (a == 1)
{
pictureBox2.Image = image;
pictureBox11.Image = image;
pictureBox9.Image = image;
}
if (a >= 1 && a <= 3)
{
pictureBox10.Image = image;
}
Im trying to make an app that can scan documents using C# and WIA. But I have come across a problem when setting up the page size property. When I run the scanning process my app throws an error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in DigiKnjiga.exe
Additional information: Exception from HRESULT: 0x80210067
I have tried this using these properties: PageSize(3097), PageWidth(3098) & PageHeight(3099), HorizontalExtent(6151) & VerticalExtent(6152). But setting any of these values throws the before mentioned exception.
Here is the event that starts the scanning process:
private void scanNew_Click(object sender, EventArgs e)
{
if (Scanner.ChosenDevice > 0)
{
Device = deviceManager.DeviceInfos[Scanner.ChosenDevice].Connect();
switch (Scanner.ColorCode)
{
case 0://color
Device.Items[1].Properties["6146"].set_Value(1);
break;
case 1://grayscale
Device.Items[1].Properties["6146"].set_Value(2);
break;
case 2://black and white
Device.Items[1].Properties["6146"].set_Value(4);
break;
}
//(DPI)
Device.Items[1].Properties["6147"].set_Value(Scanner.DPI);
Device.Items[1].Properties["6148"].set_Value(Scanner.DPI);
//brightness
Device.Items[1].Properties["Brightness"].set_Value(Scanner.Brightness);
//contrast
Device.Items[1].Properties["Contrast"].set_Value(Scanner.Contrast);
switch (Scanner.Format)
{
case 0://A3
Device.Items[1].Properties["3097"].set_Value(10);
//Device.Items[1].Properties["6151"].set_Value(11692);
//Device.Items[1].Properties["6152"].set_Value(16535);
break;
case 1://A4
Device.Items[1].Properties["3097"].set_Value(0);
//Device.Items[1].Properties["6156"].set_Value(1);
//Device.Items[1].Properties["3098"].set_Value(8267);
//Device.Items[1].Properties["3099"].set_Value(11692);
////Device.Items[1].Properties["6151"].set_Value(1165 * 2);
////Device.Items[1].Properties["6152"].set_Value(1653 * 2);
////Device.Items[1].Properties["3097"].set_Value("0");
break;
case 2://A5
Device.Items[1].Properties["3097"].set_Value(11);
//Device.Items[1].Properties["6151"].set_Value(1165);
//Device.Items[1].Properties["6152"].set_Value(1653);
break;
}
switch (Scanner.FileType)
{
case 0://JPEG
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatJPEG);
break;
case 1://PNG
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatPNG);
break;
case 2://BMP
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatBMP);
break;
case 3://TIFF
image = (WIA.ImageFile)Device.Items[1].Transfer(WIA.FormatID.wiaFormatTIFF);
break;
}
byte[] imageBytes = (byte[])image.FileData.get_BinaryData();
MemoryStream ms = new MemoryStream(imageBytes);
Image image2 = Image.FromStream(ms);
Bitmap smaller= new Bitmap(image2 , new Size(prikazZbirke.Width, prikazZbirke.Height));
prikazStrani.Size = new System.Drawing.Size(image2 .Width, image2 .Height);
prikazStrani.Location = new Point(0, 0);
prikazStrani.Image = image2 ;
image2 .Save("test.jpg");
}
}
I wonder if anyone knows the solution to the this problem and I thank you in advance for your answers. And at the same time apologise for any spelling mistakes as I am not english.
cahnge switch case as following, it could work(but be sure this property(3097) is supported in your scaner)
switch (Scanner.Format)
{
case 0://A3
Device.Properties["3097"].set_Value(10);
break;
case 1://A4
Device.Properties["3097"].set_Value(0);
break;
case 2://A5
Device.Properties["3097"].set_Value(11);
break;
}
I am working on MS chart, not having so much idea.
I have bind the chart, my next thing is to give different colors of each datapoint?
How can i do that?
My sample code is:
foreach (DataPoint pt in ChartRTM.Series["SeriesSeverity"].Points)
{
string sev = pt.YValues[1].ToString(); // this will be your value depending upon which you could set the color
switch (sev)
{
case "I":
pt.Color = Color.Red;
break;
default:
pt.Color = Color.Blue;
break;
}
}
I think you want to change the Marker color of the point :
To do this, change the switch statement :
switch (sev)
{
case "I":
pt.MarkerColor = Color.Red;
break;
default:
pt.MarkerColor = Color.Blue;
break;
}