IF blocks to LOOP - c#

I really need to shorten my code and turn massive IF operator blocks into LOOP (for, foreach).
When it is in IF blocks - code works.
When it is in FOR loop - code does not work sometimes.
Help would be nice.
IF blocks:
PictureBox tmp = new PictureBox();
tmp.Bounds = pbxDators.Bounds;
tmp.SetBounds(tmp.Location.X, tmp.Location.Y, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = 3;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = 2;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = 1;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = 0;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = -1;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = -2;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = -3;
return true;
}
return false;
And the FOR loop I tried to write to replace that massive IFs:
for (int i = -3; i <= 3; i++)
{
PictureBox tmp = new PictureBox();
tmp.Bounds = pbxDators.Bounds;
int a = 10;
if (i == 3)
{
tmp.SetBounds(tmp.Location.X, tmp.Location.Y, 1, 15);
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(2);
bumbasStiprums = 2;
return true;
}
}
else
{
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + a, 1, 15);
a = a + 10;
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(2);
bumbasStiprums = 2;
return true;
}
}
}
return false;
All that code is inside a public function which gets picturebox object as parameter and return bool value..
Why is my FOR loop not working in most cases? If the ball hits middle its sometimes OK but mostly the ball flies through the object bounds. No errors are generated.

This seems to be the code you need based on your first code:
PictureBox tmp = new PictureBox();
tmp.Bounds = pbxDators.Bounds;
tmp.SetBounds(tmp.Location.X, tmp.Location.Y, 1, 15);
for (var i = 3; i >= -3; i--)
{
if (dt.Bounds.IntersectsWith(tmp.Bounds))
{
atskanotAudio(1);
bumbasStiprums = i;
return true;
}
tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);
}
return false;

Related

WPF - print datagrid contents

I Have looked around and I have not found a solid answeer to this question. I am trying to print my datagrid content when I press a button, the main problem is that my datagrid has too much data and only whatever is shown in the screen is printing. I need It to print all data and if the data does not fit in current page create a mew page and print the rest.
Here is my solution printing Data Grid View using System.Drawing.Printing
using System.Drawing.Printing;
private int PageCounter { get; set; } = 1;
private int RowCounter { get; set; }
Print Button
private void BtnPrint_Click(object sender, EventArgs e)
{
PrintDocument printDoc = new PrintDocument();
IQueryable<PaperSize> paperSizes = printDoc.PrinterSettings.PaperSizes.Cast<PaperSize>().AsQueryable();
printDoc.DefaultPageSettings.PaperSize = paperSizes.First(ps => ps.Kind == PaperKind.A4);
printDoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pageCounter = 1;
printDoc.PrintPage += PrintDoc_PrintPage;
printDoc.Print();
}
Print Method
private void Print_Document(object sender, PrintPageEventArgs e)
{
if (e.Graphics == null)
throw new Exception("Unable to find page Graphics!");
int left = 30;
int cellLeft = left;
int top = 50;
int cellWidth = 0;
int headerHeight = 30;
string headerName = string.Empty;
string cellValue = string.Empty;
Rectangle rect = new();
int pageWidth = e.PageSettings.PaperSize.Width - 60;
int pageHeight = e.PageSettings.PaperSize.Height - 100;
Graphics g = e.Graphics;
Font font = new(FontFamily, 9);
Pen p = new(Brushes.Black, 1f);
Pen borderP = new(new SolidBrush(Color.FromArgb(240, 240, 240)), 1f);
StringFormat stringFormatCenter = new()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
StringFormat stringFormatRight = new()
{
Alignment = StringAlignment.Far,
LineAlignment = StringAlignment.Center
};
StringFormat stringFormatLeft = new()
{
LineAlignment = StringAlignment.Center
};
if (PageCounter == 1)
{
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth / 2, 30));
g.DrawRectangle(p, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 30));
top += 30;
top = 50;
g.DrawString
("Company Name"
, new Font(FontFamily, 14f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("Business Type"
, new Font(FontFamily, 12f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("Report Name"
, new Font(FontFamily, 12f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("User Name: " + SelectedUser.Name
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth / 2, 30)
, stringFormatLeft);
g.DrawString
("Report Date: " + DateTime.Now.ToString("dd-mm-yyyy hh:mm:ss")
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 30)
, stringFormatRight);
top += 30;
g.DrawString
("Login Id: " + SelectedUser.LoginId
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth / 2, 30)
, stringFormatLeft);
g.DrawString
("Printed By: " + LoggedUser.Name
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 20)
, stringFormatRight);
top += 30;
g.DrawString
("Rights detail as follows:"
, new Font(FontFamily, 8, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 20)
, stringFormatLeft);
top += 20;
}
g.FillRectangle(new SolidBrush(Color.FromArgb(234, 239, 250)), new Rectangle(left, top, pageWidth, headerHeight));
foreach (string name in PrintableRights.First().GetType().GetProperties().Select(p => p.Name))
{
if (name.Equals("SrNo"))
{
headerName = "Sr #";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 8);
}
else if (name.Equals("Code"))
{
headerName = "Code";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 20);
}
else if (name.Equals("Name"))
{
headerName = "Name";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 57);
}
else if (name.Equals("HasRight"))
{
headerName = "Right";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 15);
}
rect = new Rectangle(cellLeft, top, cellWidth, headerHeight);
g.DrawString(headerName, new Font(FontFamily, 10, FontStyle.Bold), Brushes.Black, rect, stringFormatLeft);
cellLeft += cellWidth;
}
top += headerHeight;
cellLeft = left;
while (RowCounter < PrintableRights.Count())
{
object row = PrintableRights.ElementAt(RowCounter);
cellLeft = left;
foreach (string name in row.GetType().GetProperties().Select(prop => prop.Name))
{
if (name.Equals("SrNo"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 8);
else if (name.Equals("Code"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 20);
else if (name.Equals("Name"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 57);
else if (name.Equals("HasRight"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 15);
rect = new Rectangle(cellLeft, top, cellWidth, 20);
g.DrawRectangle(borderP, rect);
PropertyInfo? prop = row.GetType().GetProperty(name);
if (prop != null)
{
if (prop.PropertyType == typeof(bool))
{
var val = prop.GetValue(row, null);
if (val != null && (bool)val)
g.DrawString("Yes", font, Brushes.Black, rect, stringFormatLeft);
else if (val != null)
g.DrawString("No", font, Brushes.Black, rect, stringFormatLeft);
}
else if (prop.PropertyType == typeof(int))
{
var val = prop.GetValue(row, null);
if (val != null)
g.DrawString(((int)val).ToString("N0"), font, Brushes.Black, rect, stringFormatRight);
else
g.DrawString(string.Empty, font, Brushes.Black, rect, stringFormatRight);
}
else if (prop.PropertyType == typeof(string))
{
var val = prop.GetValue(row, null);
if(val != null)
g.DrawString((string)val, font, Brushes.Black, rect, stringFormatLeft);
else
g.DrawString(string.Empty, font, Brushes.Black, rect, stringFormatLeft);
}
}
cellLeft += cellWidth;
}
top += 20;
if (RowCounter < PrintableRights.Count() - 1)
{
if (top > pageHeight - 10)
{
RowCounter++;
break;
}
}
RowCounter++;
}
if (RowCounter <= PrintableRights.Count() - 1)
{
if (top + 10 > pageHeight)
{
g.DrawString("Continue....", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
PageCounter++;
e.HasMorePages = true;
}
}
else if (e.HasMorePages)
{
g.DrawString("Continue....", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
PageCounter++;
}
else
{
g.DrawString("Last Page.", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
}
}

C# iOS scrolling issue

I have a Xamarin C# IOS app I wrote, using a uitableviewsource to display an unordered list. Everything looks fine until I scroll up, then the text goes up into the header and when I scroll back down it disappears.
The code for the header is as follows
public override UIView GetViewForHeader(UITableView tableView, nint section)
{
UIView view = new UIView(new Rectangle(0, 65, 320, 90));
UILabel label = new UILabel
{
Opaque = true,
TextColor = UIColor.Black, //.FromRGB(190, 0, 0);
Font = UIFont.FromName("Helvetica-Bold", 16f),
Frame = new RectangleF(12, 70, 375, 20),
Text = "View Mileage",
TextAlignment = UITextAlignment.Center
};
view.AddSubview(label);
UIButton buttonRect = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.FromRGB(191, 187, 189),
Font = UIFont.FromName("Helvetica-Bold", 16f),
Frame = new CGRect(145, 19, 100, 40)
};
buttonRect.SetTitle("Main Menu", UIControlState.Normal);
buttonRect.SetTitleColor(UIColor.Black, UIControlState.Normal);
buttonRect.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonRect.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonRect.TouchUpInside += delegate
{
UIStoryboard Storyboard = UIStoryboard.FromName("Main", null);
var webController = Storyboard.InstantiateViewController("MainMenuViewController") as MainMenuViewController;
Window = new UIWindow(UIScreen.MainScreen.Bounds);
this.Window.RootViewController = webController;
this.Window.MakeKeyAndVisible();
};
view.AddSubview(buttonRect);
UIButton buttonDate = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.Brown,
Font = UIFont.FromName("Helvetica-Bold", 13f),
Frame = new CGRect(35, 105, 50, 25)
};
buttonDate.SetTitle("Date", UIControlState.Normal);
buttonDate.SetTitleColor(UIColor.White, UIControlState.Normal);
buttonDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonDate.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonDate.TouchUpInside += delegate
{
dataList.Sort((x, y) => x.Date.CompareTo(y.Date));
if (dateCounter % 2 != 0)
dataList.Reverse();
tableView.ReloadData();
dateCounter++;
};
view.AddSubview(buttonDate);
UIButton buttonMiles = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.Brown,
Font = UIFont.FromName("Helvetica-Bold", 13f),
Frame = new CGRect(100, 105, 50, 25)
};
buttonMiles.SetTitle("Miles", UIControlState.Normal);
buttonMiles.SetTitleColor(UIColor.White, UIControlState.Normal);
buttonMiles.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonMiles.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonMiles.TouchUpInside += delegate
{
dataList.Sort((x, y) => x.Miles.CompareTo(y.Miles));
if (milesCounter % 2 == 0)
dataList.Reverse();
tableView.ReloadData();
milesCounter++;
};
view.AddSubview(buttonMiles);
UIButton buttonGas = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.Brown,
Font = UIFont.FromName("Helvetica-Bold", 13f),
Frame = new CGRect(174, 105, 50, 25)
};
buttonGas.SetTitle("Gas", UIControlState.Normal);
buttonGas.SetTitleColor(UIColor.White, UIControlState.Normal);
buttonGas.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonGas.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonGas.TouchUpInside += delegate
{
dataList.Sort((x, y) => x.Gas.CompareTo(y.Gas));
if (gasCounter % 2 == 0)
dataList.Reverse();
tableView.ReloadData();
gasCounter++;
};
view.AddSubview(buttonGas);
UIButton buttonMpg = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.Brown,
Font = UIFont.FromName("Helvetica-Bold", 13f),
Frame = new CGRect(244, 105, 50, 25)
};
buttonMpg.SetTitle("MPG", UIControlState.Normal);
buttonMpg.SetTitleColor(UIColor.White, UIControlState.Normal);
buttonMpg.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonMpg.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonMpg.TouchUpInside += delegate
{
dataList.Sort((x, y) => x.MPG.CompareTo(y.MPG));
if (mpgCounter % 2 == 0)
dataList.Reverse();
tableView.ReloadData();
mpgCounter++;
};
view.AddSubview(buttonMpg);
UIButton buttonCost = new UIButton
{
Opaque = true,
BackgroundColor = UIColor.Brown,
Font = UIFont.FromName("Helvetica-Bold", 13f),
Frame = new CGRect(314, 105, 50, 25)
};
buttonCost.SetTitle("Cost", UIControlState.Normal);
buttonCost.SetTitleColor(UIColor.White, UIControlState.Normal);
buttonCost.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
buttonCost.VerticalAlignment = UIControlContentVerticalAlignment.Center;
buttonCost.TouchUpInside += delegate
{
dataList.Sort((x, y) => x.Price.CompareTo(y.Price));
if (costCounter % 2 == 0)
dataList.Reverse();
tableView.ReloadData();
costCounter++;
};
view.AddSubview(buttonCost);
return view;
}
I am populating the table view using a UITableViewCell as follows;
public void SetData(string str0, string str1, string str2, string str3, int id, string str4)
{
lbC0.Text = str0;
lbC1.Text = str1;
lbC2.Text = str2;
lbC3.Text = str3;
lbcst.Text = str4;
lbId.Text = id.ToString();
}
public override void LayoutSubviews()
{
nfloat lbWidth = Bounds.Width / 4;
nfloat lbWidth2 = lbWidth - 35;
nfloat lbWidth3 = lbWidth2 + 70;
nfloat lbWidth4 = lbWidth3 + 70;
nfloat lbWidth5 = lbWidth4 + 65;
nfloat lbWidth6 = lbWidth5 + 75;
nfloat lbHeight = this.Bounds.Height;
if (lbC0 != null)
{
lbC0.Frame = new CGRect(2, 55, lbWidth, lbHeight);
lbC1.Frame = new CGRect(lbWidth2, 55, lbWidth, lbHeight);
lbC2.Frame = new CGRect(lbWidth3, 55, lbWidth, lbHeight);
lbC3.Frame = new CGRect(lbWidth4, 55, lbWidth, lbHeight);
lbcst.Frame = new CGRect(lbWidth5, 55, lbWidth, lbHeight);
}
}
Any help would be greatly appreciated.
Thanks
I spent weeks searching for an answer. What I finally found was I needed my subviews bounds within my TableViewCell’s bounds. This was all well and good, but I couldn’t figure out how to make it so. I tried everything I found, all to no avail. What finally ended up solving it for me was this. In my LayoutSubviews method, when setting the height of the subview, I subtracted 100 from Bounds.Height and that fixed it, it now scrolls up and down. How simple a fix... how hard to find
Here is the code I changed;
public override void LayoutSubviews()
{
nfloat lbWidth = Bounds.Width / 4;
nfloat lbWidth2 = lbWidth - 35;
nfloat lbWidth3 = lbWidth2 + 70;
nfloat lbWidth4 = lbWidth3 + 70;
nfloat lbWidth5 = lbWidth4 + 65;
nfloat lbWidth6 = lbWidth5 + 75;
-->nfloat lbHeight = this.Bounds.Height - 100;<--
if (lbC0 != null)
{
lbC0.Frame = new CGRect(2, 55, lbWidth, lbHeight);
lbC1.Frame = new CGRect(lbWidth2, 55, lbWidth, lbHeight);
lbC2.Frame = new CGRect(lbWidth3, 55, lbWidth, lbHeight);
lbC3.Frame = new CGRect(lbWidth4, 55, lbWidth, lbHeight);
lbcst.Frame = new CGRect(lbWidth5, 55, lbWidth, lbHeight);
}
}

How to assign table cell width on runtime dynamically in C#?

I have a function in devexpress report which creates table from SQL query dynamically:
readonly int[] cellWidth = { 5, 20, 30, 40, 50, 60 };// { 16, 100, 100, 30, 20, 16 };
private XRTable CreateXRTableDetail(DataTable dtAra)
{
XRTable table = new XRTable();
table.BeginInit();
table.LocationFloat = new DevExpress.Utils.PointFloat(0, 5F);
table.Borders = BorderSide.All;
int tableHeight = 0;
int tableWidth = 0;
for (int i = -1; i < 4; i++)
{
XRTableRow row = new XRTableRow();
for (int j = 0; j < 6; j++)
{
XRTableCell cell = new XRTableCell();
cell.Padding = 1;
Unit width = new Unit(cellWidth[j], UnitType.Pixel);
cell.Width = (int)width.Value;
cell.Weight = 1;
cell.TextAlignment = TextAlignment.MiddleCenter;
tableWidth += cell.Width;
if (i == -1)//Header
{
row.Height = 15;
cell.Text = dtAra.Columns[j].ColumnName;
cell.BackColor = Color.Gainsboro;
cell.Font = new Font("tahoma", 6);
}
else
{
row.Height = 40;
cell.Text = dtAra.Rows[i][j].ToString();
cell.Font = new Font("tahoma", 5);
}
row.Cells.Add(cell);
}
tableHeight += row.Height;
table.Rows.Add(row);
}
tableWidth = tableWidth / table.Rows.Count;
table.Size = new Size(tableWidth, tableHeight);
table.EndInit();
return table;
}
I assing cell widths from cellWidth array but all columns are initialising with same width.
How can I set cell width as I want?
Try this:
int width = 40;
cell.SizeF = new SizeF(cell.SizeF.Width + width, cell.SizeF.Height);

How to Print images on paper using PrintDocument

My problem is that is that my code prints the images overlapping each other. I do not know how to change the x and y positions. The printer should print 3 images per row and then move to the next row.
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
int x = 0;
int wid = 0;
int yTop = 0;
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(code, footerFont);
int headerX = 0;
int footerX = 0;
int printonpage = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
yTop = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
yTop = topMargin;
}
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, yTop, wid, height);
x += wid;
}
yTop += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, yTop);
}
}
Desired output :
I am getting :
As you can see the last digit is overlapping. I want to draw it next to the previous one
I have observed the code and found the issue.. in panel1_print u are not incrementing the values properly..
I have made the required changes now u will get the 4 bar in a line and 5th one in another line - check the attached image.
just replace ur panel1_Paint with this new code thats it you can find the changes..
I have marked them as
//start changes by Deepak
..
..
..
//end changes by Deepak
and also declare two variables loopValX and loopValY as int
here is the code..
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
int loopValX = 0;
int loopValY = -150;
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(SaveBeforePrint[serial], footerFont);
int headerX = 0;
int footerX = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
y = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
y = topMargin;
}
//start changes by Deepak
if (serial % 4 == 0)
{
loopValX = 0;
loopValY += 150;
}
else
{
loopValX += 150;
}
x += loopValX;
y += loopValY;
footerX += loopValX;
//end changes by Deepak
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, y, wid, height);
x += wid;
}
y += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, y);
}
}
You Should do it with the help of a DataGridView (That Contains Images in a Column).
The Images Will Then Print in each new row or column (by modifying as your desire)
The Following Class will do your work by passing it the whole DataGridView And Header in its constructor.
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Linq;
namespace Waqas
{
internal class ClsPrint
{
#region Variables
private int iCellHeight = 0; //Used to get/set the datagridview cell height
private int iTotalWidth = 0; //
private int iRow = 0; //Used as counter
private bool bFirstPage = false; //Used to check whether we are printing first page
private bool bNewPage = false; // Used to check whether we are printing a new page
private int iHeaderHeight = 0; //Used for the header height
private StringFormat strFormat; //Used to format the grid rows.
private ArrayList arrColumnLefts = new ArrayList(); //Used to save left coordinates of columns
private ArrayList arrColumnWidths = new ArrayList(); //Used to save column widths
private PrintDocument _printDocument = new PrintDocument();
private DataGridView gw = new DataGridView();
private string _ReportHeader;
#endregion
public ClsPrint(DataGridView gridview, string ReportHeader)
{
_printDocument.DefaultPageSettings.Landscape = true;
_printDocument.DefaultPageSettings.PaperSize.RawKind = (int)PaperKind.A4;
_printDocument.DefaultPageSettings.Margins = new Margins(30, 30, 30, 30);
//_printDocument.DefaultPageSettings.PaperSize.PaperName = "A4";
_printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);
_printDocument.BeginPrint += new PrintEventHandler(_printDocument_BeginPrint);
gw = gridview;
_ReportHeader = ReportHeader;
}
public void PrintForm()
{
//Open the print preview dialog
PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
objPPdialog.Document = _printDocument;
objPPdialog.ShowIcon = false;
objPPdialog.Text = "Print Preview";
objPPdialog.WindowState = FormWindowState.Maximized;
objPPdialog.ShowDialog();
}
private void _printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//try
//{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in gw.Columns)
{
iTmpWidth = ((int) (Math.Floor((double) ((double) GridCol.Width/
(double) iTotalWidth*(double) iTotalWidth*
((double) e.MarginBounds.Width/(double) iTotalWidth)))));
iHeaderHeight = (int) (e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 60;
// Save width and height of headers
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= gw.Rows.Count - 1)
{
DataGridViewRow GridRow = gw.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 30;
int iCount = 0;
//Check whether the current page settings allows more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString(_ReportHeader,
new Font("Calibri Light", 20, FontStyle.Bold),
new SolidBrush(Color.Black), e.MarginBounds.Left,
e.MarginBounds.Top+20 - e.Graphics.MeasureString(_ReportHeader,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToString("dd-MMM-yy hh:mm tt");
//Draw Date
e.Graphics.DrawString(strDate,
new Font("Calibri Light", 12, FontStyle.Bold), Brushes.Black,
e.MarginBounds.Left-20 +
(e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Width),
e.MarginBounds.Top+30 - e.Graphics.MeasureString(_ReportHeader,
new Font(new Font(gw.Font, FontStyle.Bold),
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top+30;
DataGridViewColumn[] _GridCol = new DataGridViewColumn[gw.Columns.Count];
int colcount = 0;
//Convert ltr to rtl
foreach (DataGridViewColumn GridCol in gw.Columns)
{
_GridCol[colcount++] = GridCol;
}
for (int i =0; i <= (_GridCol.Count() - 1); i++)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(_GridCol[i].HeaderText,
new Font("Calibri Light", 12, FontStyle.Bold),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
DataGridViewCell[] _GridCell = new DataGridViewCell[GridRow.Cells.Count];
int cellcount = 0;
//Convert ltr to rtl
foreach (DataGridViewCell Cel in GridRow.Cells)
{
_GridCell[cellcount++] = Cel;
}
//Draw Columns Contents
for (int i =0; i <=(_GridCell.Count() - 1); i++)
{
if (_GridCell[i].Value != null)
{
if (_GridCell[i].GetType() != typeof (DataGridViewImageCell))
{
e.Graphics.DrawString(_GridCell[i].FormattedValue.ToString(),
new Font("Calibri Light", 10),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount],
(float) iTopMargin,
(int) arrColumnWidths[iCount], (float) iCellHeight),
strFormat);
}
else
{
Image img = Common.byteArrayToImage((byte[]) _GridCell[i].Value);
Rectangle m = new Rectangle((int) arrColumnLefts[iCount],iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight);
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
//Drawing Cells Borders
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
//}
//catch (Exception exc)
//{
// KryptonMessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
//}
}
private void _printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in gw.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (Exception ex)
{
KryptonMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
as
ClsPrint _ClsPrint = new ClsPrint(myDataGridView, "MyHeader");
_ClsPrint.PrintForm();
Your position variables are being declared inside the loop, meaning that they are reset for each pass through the loop. Keep position variables for X and Y outside of the loop over serial and adjust it for the total width (and height, if you start a new row of barcodes) of each barcode.

How to draw only visible data XNA My method doesn't work

I have a 10*10 plane of cubes. I want only visible cubes to be drawn, so I use a Bounding frustum. The problem is that when the first cube from the grid (at location 0,0) gets out of the frustum, all cubes disappear.
Here is my code in Cube.cs:
public class Cube
{
Vector3 scale;
float textureScale;
GraphicsDevice device;
Effect effect;
VertexBuffer vertexBuffer;
Texture2D texture;
public Vector3 GlobalPosition = new Vector3(0, 0, 0);
public Vector3[] vertices = new Vector3[36];
public Cube(Vector3 scale, float textureScale, Effect effect, Texture2D texture, GraphicsDevice device)
{
this.scale = scale;
this.textureScale = textureScale;
this.device = device;
this.effect = effect;
this.texture = texture;
vertices[0] = new Vector3(-1, 1, -1);
vertices[1] = new Vector3(-1, -1, -1);
vertices[2] = new Vector3(1, -1, -1);
vertices[3] = new Vector3(1, -1, -1);
vertices[4] = new Vector3(1, 1, -1);
vertices[5] = new Vector3(-1, 1, -1);
//Front
vertices[6] = new Vector3(1, -1, 1);
vertices[7] = new Vector3(-1, -1, 1);
vertices[8] = new Vector3(-1, 1, 1);
vertices[9] = new Vector3(-1, 1, 1);
vertices[10] = new Vector3(1, 1, 1);
vertices[11] = new Vector3(1, -1, 1);
//Bottom
vertices[12] = new Vector3(-1, -1, -1);
vertices[13] = new Vector3(-1, -1, 1);
vertices[14] = new Vector3(1, -1, -1);
vertices[15] = new Vector3(1, -1, 1);
vertices[16] = new Vector3(1, -1, -1);
vertices[17] = new Vector3(-1, -1, 1);
//Top
vertices[18] = new Vector3(1, 1, -1);
vertices[19] = new Vector3(-1, 1, 1);
vertices[20] = new Vector3(-1, 1, -1);
vertices[21] = new Vector3(-1, 1, 1);
vertices[22] = new Vector3(1, 1, -1);
vertices[23] = new Vector3(1, 1, 1);
//Left
vertices[24] = new Vector3(-1, -1, 1);
vertices[25] = new Vector3(-1, -1, -1);
vertices[26] = new Vector3(-1, 1, -1);
vertices[27] = new Vector3(-1, 1, -1);
vertices[28] = new Vector3(-1, 1, 1);
vertices[29] = new Vector3(-1, -1, 1);
//Right
vertices[30] = new Vector3(1, -1, -1);
vertices[31] = new Vector3(1, -1, 1);
vertices[32] = new Vector3(1, 1, -1);
vertices[33] = new Vector3(1, -1, 1);
vertices[34] = new Vector3(1, 1, 1);
vertices[35] = new Vector3(1, 1, -1);
for (int i = 0; i < 36; i++)
{
vertices[i] = vertices[i] * scale + GlobalPosition;
}
VertexPositionNormalTexture[] verticesList = GetVPNT();
vertexBuffer = new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, verticesList.Length, BufferUsage.WriteOnly);
vertexBuffer.SetData<VertexPositionNormalTexture>(verticesList.ToArray());
}
public void Draw(Matrix View, Matrix Projection, Vector3 pos)
{
effect.CurrentTechnique = effect.Techniques["Textured"];
effect.Parameters["xWorld"].SetValue(Matrix.Identity * Matrix.CreateTranslation(pos));
effect.Parameters["xView"].SetValue(View);
effect.Parameters["xProjection"].SetValue(Projection);
effect.Parameters["xTexture"].SetValue(texture);
effect.Parameters["xEnableLighting"].SetValue(true);
effect.Parameters["xLightDirection"].SetValue(new Vector3(30, 30, 30));
effect.Parameters["xAmbient"].SetValue(0.5f);
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
device.SetVertexBuffer(vertexBuffer);
device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexBuffer.VertexCount / 3);
}
}
public VertexPositionNormalTexture[] GetVPNT()
{
VertexPositionNormalTexture[] vpnt = new VertexPositionNormalTexture[36];
Vector2[] texCoords = CalculateTexCoords(vertices, "tile");
for (int i = 0; i < 36; i++)
{
vpnt[i] = new VertexPositionNormalTexture(vertices[i], new Vector3(0, 0, 1), texCoords[i]);
}
return vpnt;
}
public Vector2[] CalculateTexCoords(Vector3[] vec, string type)
{
List<Vector2> texCoords = new List<Vector2>();
for (int i = 0; i < 12; i++)
{
if (AllEqual<float>(vertices[i * 3 + 0].X, vertices[i * 3 + 1].X, vertices[i * 3 + 2].X))
{
Vector2[] normvec = new Vector2[3];
normvec[0] = TexNorm(new Vector2(vertices[i * 3 + 0].Z, vertices[i * 3 + 0].Y), type);
normvec[1] = TexNorm(new Vector2(vertices[i * 3 + 1].Z, vertices[i * 3 + 1].Y), type);
normvec[2] = TexNorm(new Vector2(vertices[i * 3 + 2].Z, vertices[i * 3 + 2].Y), type);
texCoords.AddRange(normvec);
}
if (AllEqual<float>(vertices[i * 3 + 0].Y, vertices[i * 3 + 1].Y, vertices[i * 3 + 2].Y))
{
Vector2[] normvec = new Vector2[3];
normvec[0] = TexNorm(new Vector2(vertices[i * 3 + 0].X, vertices[i * 3 + 0].Z), type);
normvec[1] = TexNorm(new Vector2(vertices[i * 3 + 1].X, vertices[i * 3 + 1].Z), type);
normvec[2] = TexNorm(new Vector2(vertices[i * 3 + 2].X, vertices[i * 3 + 2].Z), type);
texCoords.AddRange(normvec);
}
if (AllEqual<float>(vertices[i * 3 + 0].Z, vertices[i * 3 + 1].Z, vertices[i * 3 + 2].Z))
{
Vector2[] normvec = new Vector2[3];
normvec[0] = TexNorm(new Vector2(vertices[i * 3 + 0].X, vertices[i * 3 + 0].Y), type);
normvec[1] = TexNorm(new Vector2(vertices[i * 3 + 1].X, vertices[i * 3 + 1].Y), type);
normvec[2] = TexNorm(new Vector2(vertices[i * 3 + 2].X, vertices[i * 3 + 2].Y), type);
texCoords.AddRange(normvec);
}
}
return texCoords.ToArray();
}
public bool AllEqual<T>(params T[] values)
{
if (values == null || values.Length == 0)
return true;
return values.All(v => v.Equals(values[0]));
}
public Vector2 TexNorm(Vector2 vecIn, string type)
{
Vector2 vec = new Vector2();
//Remove negative coordinates
if (vecIn.Y < 0)
vec.Y = 0;
if (vecIn.X < 0)
vec.X = 0;
switch (type)
{
case "stretch":
{
if (vecIn.X > 0)
vec.X = 1;
if (vecIn.Y > 0)
vec.Y = 1;
break;
}
case "tile":
{
if (vecIn.X > 0)
vec.X = textureScale;
if (vecIn.Y > 0)
vec.Y = textureScale;
break;
}
}
return vec;
}
public bool IsVisible(Matrix VP)
{
BoundingFrustum bf = new BoundingFrustum(VP);
bool isVis = true;
//Check weather at least one vertices are out of the frustum
for (int i = 0; i < 36; i++)
{
if (bf.Contains(vertices[i]) != ContainmentType.Contains)
{
isVis = false;
break;
}
}
return isVis;
}
}
Draw() method in Main.cs:
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 10; k++)
{
Cube cube = new Cube(Vector3.One, 1, effect, woodTexture, device);
if (cube.IsVisible(View * Projection))
{
cube.Draw(View, Projection, new Vector3(2 * i, 0, 2 * k));
}
}
}
I would also like if you can give me link to an atlas texturing tutorial/sample, Thanks!
Your cube.IsVisible(...) method does not take into account latter transformation you're applying when you're drawing the cube, i.e you're always checking against your original cube, not the transformed ones.
Please reference this answer as it touches both your culling problem (frustum-box) as well as instancing.

Categories