I am trying to create a graph that will show the progress of a workout. Every five button clicks a tick should be added to the graph. This is a example of how it should look.
For demonstration purposes I am using a button click, In production the clicks will be every twenty revolutions of a wheel.
private int counter = 0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
// code will go here
}
Thanks in advance
You can use either a Bitmap Buffer or a panel to draw on. Here is a headstart: Just a sample.
reference.
This solution is based on WinForms & Panel_Paint(). You may try to add vertical Progress Label and Chart's Y Axis value labeling.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1(){
InitializeComponent();
}
private int counter = 0;
private int px = 10;
private int py = 180;
private int total5Clicks = 0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
label1.Text = "Total Clicks = " + counter.ToString();
if (Math.Abs(counter % 5) == 0){
if (Math.Abs(counter / 5) > 0){
total5Clicks = total5Clicks + 1;
PaintOnChartPanel(total5Clicks);}
}
}
private void panel1_Paint(object sender, PaintEventArgs e){
}
private void PaintOnChartPanel(int total5Times)
{
//Add a new Panel Paint EventHandler
panel1.Paint += new PaintEventHandler(panel1_Paint);
using (Graphics g = this.panel1.CreateGraphics())
{
Brush brush = new SolidBrush(Color.Green);
g.FillRectangle(brush, px, py, 20, 20);
Pen pen = new Pen(new SolidBrush(Color.White));
g.DrawRectangle(pen, px, py, 20, 20);
//add each total5Click into chart block
g.DrawString((total5Times).ToString(), new Font("Arial", 7),
new SolidBrush(Color.AntiqueWhite),
px + 1, py+8, StringFormat.GenericDefault);
pen.Dispose();}
if (py > 20){
py = py - 20;}
else{
MessageBox.Show("Reached Top of the Panel");
if (px < 200){
px = px + 20;
py = 180;}
else{
MessageBox.Show("Reached Right of the Panel");
}
}
}
}
}
Output Form:
You can determine if you have a multiple of five with
bool drawTickMark = clicks % 5 == 0;
% is the modulo operator which returns the remainder of an integer division. E.g. 13 % 5 = 3 and 13 / 5 = 2 because 2 * 5 + 3 = 13.
clicks % 5 will be zero for clicks = 0, 5, 10, 15, ...
I'm not much of an ASP.NET guy but here's an algorithm you can use to draw the squares
int perColumn = Height / squareSize;
int totalColumns = (squareCount / perColumn) + 1;
for (int y = 0; y <= totalColumns - 1; y++)
{
int itemCount = squareCount - (y * perColumn);
if (itemCount > perColumn)
itemCount = perColumn;
for (int x = 0; x <= itemCount - 1; x++)
e.Graphics.FillRectangle(RandomBrush, New Rectangle((column * SquareSize) + 3, (i * SquareSize) + 3, SquareSize - 2, SquareSize - 2))
public sealed class ClickGraph : Control
{
private int squareCount = 1;
public int SquareCount
{
get
{
return squareCount;
}
set
{
squareCount = value;
Invalidate();
}
}
private int squareSize = 25;
public int SquareSize
{
get
{
return squareSize;
}
set
{
squareSize = value;
Invalidate();
}
}
public ClickGraph()
{
SetStyle(ControlStyles.ResizeRedraw, true);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
int perColumn = Height / squareSize;
int totalColumns = (squareCount / perColumn) + 1;
for (int y = 0; y <= totalColumns - 1; y++)
{
int itemCount = squareCount - (y * perColumn);
if (itemCount > perColumn)
itemCount = perColumn;
for (int x = 0; x <= itemCount - 1; x++)
e.Graphics.FillRectangle(RandomBrush, New Rectangle((column * SquareSize) + 3, (i * SquareSize) + 3, SquareSize - 2, SquareSize - 2))
}
}
}
Related
Im doing school project. My task is to write a small Winform application that represents the Bezier Curve, but with some constraints.
I did almost everything, just one more step is ahead of me.
The whole program starts with an empty canvas, then the user can click on it, and a circle is drawn. After every 4th click, the bezier curve appears to that polygon. Now comes my problem.
What I am stuck with is that I have to controll somehow where the 5th click is going to be. It must be on a line that comes from 2 points: the 3rd and 4th points.
Can anybody help me with this? I have really no idea how to even start.
So far, this is my code.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace grafika_beadando_kettesert
{
public partial class MainForm : Form
{
Graphics g;
int counter = 0;
Pen PenBlack = Pens.Black; //ezzel a tollal rajzolom a vonalat
Pen PenCurve = new Pen(Color.Blue, 3f); //ezzel a tollal rajzolom a görbét
Brush PenPoint; //Ezzel töltöm ki a pontot
int size = 4; // a lerakott pont mérete
int found = -1;
List<PointF> Points = new List<PointF>(); //ebbe a listába tárolom a pontokat
PointF p0, p1;
public MainForm()
{
InitializeComponent();
PenPoint = new SolidBrush(canvas.BackColor);
this.DoubleBuffered = true;
}
private void canvas_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
for (int i = 0; i < Points.Count - 1; i++) // mindig meg kell rajzolni az eddig meghúzott vonalakat a polygonból újra
g.DrawLine(PenBlack, Points[i], Points[i + 1]);
if (counter == 4)
{
DrawBeziergorbe();
counter = 0;
}
for (int i = 0; i < Points.Count; i++) // ezzel rajzolom meg az eddig felrakott pontokat újra
{
g.FillEllipse(PenPoint, Points[i].X - size, Points[i].Y - size, 2 * size, 2 * size);
g.DrawEllipse(PenBlack, Points[i].X - size, Points[i].Y - size, 2 * size, 2 * size);
}
}
private void canvas_MouseUp(object sender, MouseEventArgs e)
{
found = -1;
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (found != -1)
{
Points[found] = e.Location;
canvas.Invalidate();
}
}
private void canvas_MouseDown(object sender, MouseEventArgs e)
{
for (int i = 0; i < Points.Count; i++)
{
if (Math.Abs(Points[i].X - e.X) <= size && Math.Abs(Points[i].Y - e.Y) <= size)
{
found = i;
break;
}
}
if (found == -1)
{
Points.Add(e.Location); //ha nincs túl közel a lerakott pont egy jelenlegihez, akkor hozzáadja a
//"Points" listához, hogy innen kiolvasva újra belehessen rajzolni
found = Points.Count - 1;
counter++;
canvas.Invalidate();
}
}
private void DrawBeziergorbe() //Mivel n-ed fokú bezier görbe kell, ezért használom a binomiálisos megoldást
{
int n = Points.Count - 1;
double t = 0;
double h = 1.0 / 500.0;
double b = 0.0;
p0 = new PointF(0, 0);
for (int i = 0; i <= n; i++)
{
b = B(n, i, t);
p0.X += (float)(b * Points[i].X);
p0.Y += (float)(b * Points[i].Y);
}
while (t < 1)
{
t += h;
p1 = new PointF(0, 0);
for (int i = 0; i <= n; i++)
{
b = B(n, i, t);
p1.X += (float)(b * Points[i].X);
p1.Y += (float)(b * Points[i].Y);
}
g.DrawLine(PenCurve, p0, p1);
p0 = p1;
}
}
private double B(int n, int i, double t)
{
return Binom(n, i) * (Math.Pow(1 - t, n - i) * Math.Pow(t, i));
}
private uint Binom(int n, int k)
{
if (n == 0) return 0;
else if (k == 0 || k == n) return 1;
else return Binom(n - 1, k - 1) + Binom(n - 1, k);
}
}
}
You can simply project the click position on the desired line.
If c is the click position and A and B are the two last control points, then the projected position p is:
d = B - A
p = A + dot(c - A, d) / dot(d, d) * d
Using a 2d array of buttons implemented and placed on a form.
Button[,] tmpButton = new Button[x, y];
private void DrawGrid()
{
int ButtonWidth = 48;
int ButtonHeight = 48;
int start_x = 88;
int start_y = 200;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
tmpButton[i, j] = new Button();
tmpButton[i, j].Top = start_x + (i * ButtonHeight);
tmpButton[i, j].Left = start_y + (j * ButtonWidth);
tmpButton[i, j].Width = ButtonWidth;
tmpButton[i, j].Height = ButtonHeight;
tmpButton[i, j].Click += new EventHandler(BTN_Grid_Click);
this.Controls.Add(tmpButton[i, j]);
}
}
}
If a random location (x,y) is set true within the grid with the intention of guessing (by clicking on the surrounding grid buttons) it's location. If the location is !true it should return left right up down pointing to the random location we set earlier. If the true location is up and left, it should return whichever it is closest too.
What would be the best way to implement something like this?
This is getting close, but something I can't see is off a bit ...
public String GetDirection()
{
int xd = Guess.X - Clue.X;
int yd = Guess.Y - Clue.Y;
if(Math.Abs(xd) <= Math.Abs(yd))
return (xd <= 0) ? "Left" : "Right";
else
return (yd <= 0) ? "Down" : "Up";
}
Here is a visual representation of what is happening ...
Alright so you had most of it right however you made a easy mistake. When you create the buttons you're rendering from left to right then top to bottom which creates the height as the x position then the width as the y position. So when you go and correlate the guess to the correct position you forget that you did this and assume x is the width.
Here's my implementation which fixed this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UpDownLeftRight {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.Load += new System.EventHandler(this.Form1_Load);
}
public int[] winner = new int[2];
public Button[,] tmpButton = new Button[10, 10];
private void Form1_Load(object sender, EventArgs e) {
Random r = new Random();
int ButtonWidth = 48;
int ButtonHeight = 48;
int start_x = 0;
int start_y = 0;
winner = new int[] { r.Next(0, 10), r.Next(0, 10) };
this.Size = new Size((ButtonWidth * 11), (ButtonHeight * 11));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
tmpButton[i, j] = new Button();
tmpButton[i, j].Left = start_x + (i * ButtonWidth);
tmpButton[i, j].Top = start_y + (j * ButtonHeight);
tmpButton[i, j].Width = ButtonWidth;
tmpButton[i, j].Height = ButtonHeight;
tmpButton[i, j].Font = new Font(FontFamily.GenericMonospace, 17);
tmpButton[i, j].Click += new EventHandler(BTN_Grid_Click);
this.Controls.Add(tmpButton[i, j]);
}
}
}
public void BTN_Grid_Click(object o, EventArgs e) {
int[] guess = new int[2];
for (int i = 0; i != tmpButton.GetLength(1); i++) {
for (int j = 0; j != tmpButton.GetLength(0); j++) {
if (tmpButton[i, j] == o) {
guess = new int[] { i, j };
}
}
}
int xDist = guess[0] - winner[0];
int yDist = guess[1] - winner[1];
string possible = "˂˃˄˅";
if (xDist > 0) { possible = possible.Replace("˃", ""); }
if (xDist < 0) { possible = possible.Replace("˂", ""); }
if (xDist == 0) { possible = possible.Replace("˂", ""); possible = possible.Replace("˃", ""); }
if (yDist > 0) { possible = possible.Replace("˅", ""); }
if (yDist < 0) { possible = possible.Replace("˄", ""); }
if (yDist == 0) { possible = possible.Replace("˄", ""); possible = possible.Replace("˅", ""); }
((Button)o).Text = possible;
}
}
}
I am currently trying new techniques for going through every pixel on a image and doing some minor process for each. Here is my active code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace ImageProcessingExmp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Timer timer = new Timer();
private void Form1_Load(object sender, EventArgs e)
{
timer.Tick += ChangeColor;
timer.Interval = 1;
timer.Start();
pictureBox1.Width = this.Width;
pictureBox1.Height = this.Height;
pictureBox1.Left = 0;
pictureBox1.Top = 0;
this.WindowState = FormWindowState.Maximized;
}
int timerinc = 0;
public void ChangeColor(object sender, EventArgs e)
{
if (timerinc>=240)
{
timer.Stop();
}
timerinc+=10;
Bitmap bmp = (Bitmap)new Bitmap(this.Width,this.Height);
Benchmark.Start();
///////////////////////////////////////////////////////////////////////////////
// Get the area to be painted
Rectangle areaToPaint = new Rectangle();
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = data.Stride;
Random rnd = new Random(DateTime.Now.Millisecond);
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Check this is not a null area
// Go through the draw area and set the pixels as they should be
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
// layer.GetBitmap().SetPixel(x, y, m_colour);
byte x2 = Convert.ToByte(x > 255 ? 0 : x);
byte y2 = Convert.ToByte(y > 255 ? 0 : y);
ptr[(x * 3) + y * stride] = x2;
ptr[(x * 3) + y * stride + 1] = y2;
ptr[(x * 3) + y * stride + 2] = 255;
}
}
}
bmp.UnlockBits(data);
/////////////////////////////////////////////////////////////////////////////////
Benchmark.End();
double seconds = Benchmark.GetSeconds();
//MessageBox.Show(seconds.ToString());
richTextBox1.Text += seconds.ToString()+'\n' ;
richTextBox2.Text += DateTime.Now.Second.ToString()+'\n';
pictureBox1.Image= bmp;
String[] lines = richTextBox1.Text.Split('\n');
double avg = 0;
double sum = 0;
double num = 0;
foreach (var line in lines)
{
// MessageBox.Show(line);
double tet = 0;
Double.TryParse(line, out tet);
sum += tet;
num++;
}
avg = sum / num;
label1.Text = "fps = " + (1/avg).ToString();
}
public class Benchmark
{
private static DateTime startDate = DateTime.MinValue;
private static DateTime endDate = DateTime.MinValue;
public static TimeSpan Span { get { return endDate.Subtract(startDate); } }
public static void Start() { startDate = DateTime.Now; }
public static void End() { endDate = DateTime.Now; }
public static double GetSeconds()
{
if (endDate == DateTime.MinValue) return 0.0;
else return Span.TotalSeconds;
}
}
}
}
I need to get the FPS to around, say, 90 fps. How can I do this? Do I need to use something other than C#? The current fps is about 7.
EDIT 1
Stack overflow edited out some of my text.. weird...
Here is the real unsafe code.
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Check this is not a null area
// Go through the draw area and set the pixels as they should be
for (int y = 0; y< bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
// layer.GetBitmap().SetPixel(x, y, m_colour);
byte x2 = Convert.ToByte(x > 255 ? 0 : x);
byte y2 = Convert.ToByte(y > 255 ? 0 : y);
ptr[(x * 3) + y * stride] = x2;
ptr[(x * 3) + y * stride + 1] = y2;
ptr[(x * 3) + y * stride + 2] = 255;
}
}
}
Edit 2
Wow... it did it again... I am replacing the less than symbols with (LESSTHAN)
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Check this is not a null area
// Go through the draw area and set the pixels as they should be
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
// layer.GetBitmap().SetPixel(x, y, m_colour);
byte x2 = Convert.ToByte(x > 255 ? 0 : x);
byte y2 = Convert.ToByte(y > 255 ? 0 : y);
ptr[(x * 3) + y * stride] = x2;
ptr[(x * 3) + y * stride + 1] = y2;
ptr[(x * 3) + y * stride + 2] = 255;
}
}
}
Edit 3
Tried changing the format to PixelFormat.Format32bppPArgb. Didn't work. Got this:
Click to view image
Edit 4
Plenty of changes to the code. Here is the current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace ImageProcessingExmp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Timer timer = new Timer();
private void Form1_Load(object sender, EventArgs e)
{
timer.Tick += ChangeColor;
timer.Interval = 1;
timer.Start();
pictureBox1.Width = this.Width;
pictureBox1.Height = this.Height;
pictureBox1.Left = 0;
pictureBox1.Top = 0;
this.WindowState = FormWindowState.Maximized;
bmp=(Bitmap)new Bitmap(this.Width, this.Height);
}
int timerinc = 0;
int stride;
Bitmap bmp;
BitmapData data;
public void ChangeColor(object sender, EventArgs e)
{
timerinc+=10;
Benchmark.Start();
///////////////////////////////////////////////////////////////////////////////
data= bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
stride = data.Stride;
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Check this is not a null area
// Go through the draw area and set the pixels as they should be
for (int y = 0; y < bmp.Height; y++)
{
int yTimeStride = y * stride;
byte y2 = (byte)(y > 255 ? 0 : y);
for (int x = 0; x < bmp.Width; x++)
{
int addressToAssign = (x * 3) + yTimeStride;
byte x2 = (byte)(x > 255 ? 0 : x);
ptr[addressToAssign] = x2;
ptr[addressToAssign + 1] = y2;
ptr[addressToAssign + 2] = x2;
}
}
}
bmp.UnlockBits(data);
/////////////////////////////////////////////////////////////////////////////////
Benchmark.End();
double seconds = Benchmark.GetSeconds();
//MessageBox.Show(seconds.ToString());
richTextBox1.Text += seconds.ToString()+'\n' ;
richTextBox2.Text += DateTime.Now.Second.ToString()+'\n';
pictureBox1.Image= bmp;
String[] lines = richTextBox1.Text.Split('\n');
double avg = 0;
double sum = 0;
double num = 0;
foreach (var line in lines)
{
// MessageBox.Show(line);
double tet = 0;
Double.TryParse(line, out tet);
sum += tet;
num++;
}
avg = sum / num;
label1.Text = "fps = " + (1/avg).ToString();
tst1.Add(1/avg*20);
if (timerinc >= 500)
{
timer.Stop();
Bitmap bmp2 = new Bitmap(pictureBox2.Width,pictureBox2.Height);
data = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
stride = data.Stride;
unsafe
{
byte* ptr = (byte*)data.Scan0;
// Check this is not a null area
// Go through the draw area and set the pixels as they should be
for (int x = 0; x < tst1.Count; x++)
{
for (int y = 0; y < (int)tst1[x]; y++)
{
//MessageBox.Show(x.ToString());
if (y<bmp2.Height)
{
ptr[(x * 3) + (int)y * stride] = 255;//b
ptr[(x * 3) + (int)y * stride + 1] =0;//g
ptr[(x * 3) + (int)y * stride + 2] = 255;//r
}
}
}
}
bmp2.UnlockBits(data);
pictureBox2.Image = bmp2;
}
}
public List<double> tst1 = new List<double>();
public class Benchmark
{
private static DateTime startDate = DateTime.MinValue;
private static DateTime endDate = DateTime.MinValue;
public static TimeSpan Span { get { return endDate.Subtract(startDate); } }
public static void Start() { startDate = DateTime.Now; }
public static void End() { endDate = DateTime.Now; }
public static double GetSeconds()
{
if (endDate == DateTime.MinValue) return 0.0;
else return Span.TotalSeconds;
}
}
}
}
Unfortunately, this only gets me 5 fps. I am starting to believe that painting on a bitmap then putting it onto the screen is not the way to quickly render games. Does anybody know another way?
Considering the code you're benchmarking:
rnd is useless (wrong copy/paste?)
you're doing way too much multiplication, consider using:
Code:
for (int y = 0; y < bmp.Height; y++)
{
int yTimeStride = y * stride;
byte y2 = Convert.ToByte(y > 255 ? 0 : y);
for (int x = 0; x < bmp.Width; x++)
{
int addressToAssign = (x * 3) + yTimeStride;
byte x2 = Convert.ToByte(x > 255 ? 0 : x);
ptr[addressToAssign] = x2;
ptr[addressToAssign + 1] = y2;
ptr[addressToAssign + 2] = 255;
}
}
This will reduce multiplication with y from Height*Width*3 to Height and reduce multiplication with x by 3.
I have a ball bouncing off of paddles and walls as desired, i have then added a singular brick via the draw.Rectangle tool and had the ball bounce off of this and then change its colour but could not make it invisible to stop any further collisions.
I am using an array for my bricks as i can have many and can turn them true or false after being hit
My issue is that i am trying to get the ball to collide with said array bricks, but cannot for the life of me figure it out even with as much googling as possible. here is the snippet of my code i think 'should' work for the collision
for (int i = 0; 1 < brickLive.Length; i++)
if ((y == brickLocation[i, 0]) && (x >= brickLocation[0, i]) && (x <= (brickLocation[0, i] + 60)))
yChange = -yChange;
to my understanding this code is saying for the value of i check if ball coords are in the parameters of a bricks location. if it is then change direction.
with the current code it runs fine until i start the game (i click the insert button and that enables the bounce button to work)
here is my full code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Breakout
{
public partial class Form1 : Form
{
private int x, y, x2, y2;
private int xChange, yChange;
int bat, batX, batXX, mouseX;
private Graphics paper;
private Pen pen, pen2, pen3;
private Pen brkpen;
private Random ranNum;
int brkLength = 60;
int brkHeight = 20;
int[,] brickLocation = { { 0, 100 }, { 61, 100 }, { 122, 100 } };
bool[] brickLive = { true, true, true };
public Form1()
{
InitializeComponent();
paper = picDisplayBat.CreateGraphics();
pen = new Pen(Color.Red);
pen.Width = 10;
ranNum = new Random();
paper = picDisplayBat.CreateGraphics();
pen = new Pen(Color.Blue);
pen.Width = 3;
paper = picDisplayBat.CreateGraphics();
pen2 = new Pen(Color.Red);
pen.Width = 3;
picDisplayBat.MouseMove += new
System.Windows.Forms.MouseEventHandler(picDraw_MouseMove);
paper = picDisplayBat.CreateGraphics();
brkpen = new Pen(Color.Black);
brkpen.Width = 3;
//paper = picDisplayBat.CreateGraphics();
//pen3 = new Pen(Color.Green);
//pen3.Width = 5;
}
private void picDraw_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) //DRAWING THE BAT TO MOVE WITH MOUSE
{
//paper.Clear(Color.White);
mouseX = e.X;
}
private void btnInsert_Click_1(object sender, EventArgs e)
{
{
btnBounce.Visible = true;
}
}
private void btnBounce_Click_1(object sender, EventArgs e)
{
{
timer1.Interval = 25;
timer1.Enabled = true;
x = ranNum.Next(1, picDisplayBat.Height);
y = ranNum.Next(1, picDisplayBat.Width);
xChange = ranNum.Next(1, 10); yChange = ranNum.Next(1, 10);
for (int i = 0; i < brickLive.Length; i++)
{
paper.DrawRectangle(brkpen, brickLocation[i, 0], brickLocation[i, 1], brkLength, brkHeight);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
{
x = x + xChange;
y = y + yChange;
if (x >= picDisplayBat.Width)
xChange = -xChange;
if (y >= picDisplayBat.Height)
yChange = -yChange;
if (x <= 0)
xChange = -xChange;
if (y <= 0)
yChange = -yChange;
if ((y > picDisplayBat.Height - 20) && (x >= batX + 10) && (x <= batX + 50))
yChange = -yChange;
if ((y < picDisplayBat.Height - 295) && (x >= batX + 10) && (x <= batX + 50))
yChange = -yChange;
for (int i = 0; 1 < brickLive.Length; i++)
if ((y == brickLocation[i, 0]) && (x >= brickLocation[0, i]) && (x <= (brickLocation[0, i] + 60)))
yChange = -yChange;
paper.Clear(Color.White);
paper.DrawRectangle(pen, mouseX + 10, picDisplayBat.Height - 20, 50, 10); //bat 1
paper.DrawEllipse(pen, x, y, 10, 10); //ball
paper.DrawRectangle(pen2, mouseX + 10, picDisplayBat.Height - 295, 50, 10); //bat2
//paper.DrawRectangle(pen3, x2, y2, 60, 10);
bat = mouseX;
batX = mouseX;
batXX = mouseX;
for (int i = 0; i < brickLive.Length; i++)
{
paper.DrawRectangle(brkpen, brickLocation[i, 0], brickLocation[i, 1], brkLength, brkHeight);
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
paper.Clear(Color.White);
}
}
}
This looks wrong to me.
if ((y == brickLocation[i, 0])
&& (x >= brickLocation[0, i])
&& (x <= (brickLocation[0, i] + 60)))
It seems to me you should always have [i, ... for the brick array position, so either [i, 0] for tests against the horizontal component and [i, 1] for the vertical component.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to draw an image in my Windows Form Application. I drew instead of the picture some rectangles but I want to replace them somehow with a certain image.
I added the whole code and the problem is in the draw function. Can anybody help?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
namespace kiralyno
{
public partial class Form2 : Form
{
public static int p = 1;
public static int o = 1;
public float[] x1 = new float[80000];
public float[] y1 = new float[80000];
public string hely = " ";
public int db = 0;
public int[] v = new int[80000];
public static string a;
public string s = " ";
public static int n = Form1.n;
public float x = 0, y = 0, w = 450 / n, h = 450 / n;
public int helyes(int i, int k)
{
for (int j = 1; j <= k - 1; j++)
if ((v[j] == i) || (Math.Abs(k - j) == Math.Abs(i - v[j])))
return 0;
return 1;
}
public void kiir(int k)
{
for (int j = 1; j <= k; j++)
{
s += Convert.ToString(v[j]);
if (j != n) s += " ";
}
a = s;
megoldas.Items.Add(a);
s = "";
a = "";
}
public void back(int k)
{
for (int i = 1; i <= n; i++)
{
if (helyes(i, k) == 1)
{
v[k] = i;
if (k == n)
{
kiir(k);
draw();
Thread.Sleep(500);
sakktabla(0, 0, w, h);
db++;
}
else back(k + 1);
}
}
}
public void draw()
{
// Image newImage = Image.FromFile("D:/Akos/Visual/Projects/kiralyno/kir.png");
Graphics g = panel1.CreateGraphics();
for (int m = 1; m <= n; m++)
{
g.DrawRectangle(new Pen(Brushes.Blue), x1[v[m]], y1[m], w, h);
g.FillRectangle(Brushes.Blue, x1[v[m]], y1[m], w, h);
Thread.Sleep(200);
}
}
public Form2()
{
InitializeComponent();
}
public void sakktabla(float x, float y, float w, float h)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if ((i + j) % 2 == 0)
{
Graphics g = panel1.CreateGraphics();
g.DrawRectangle(new Pen(Brushes.Black), x, y, w, h);
g.FillRectangle(Brushes.Black, x, y, w, h);
x1[p] = x;
x = x + 450 / n;
}
else
{
Graphics g = panel1.CreateGraphics();
g.DrawRectangle(new Pen(Brushes.White), x, y, w, h);
g.FillRectangle(Brushes.White, x, y, w, h);
x1[p] = x;
x = x + 450 / n;
}
p++;
}
y1[o] = y;
for (int m = 1; m <= n; m++)
{
y1[n * m + o] = y1[o];
}
o++;
y = y + 450 / n;
x = 0;
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
sakktabla(0, 0, w, h);
}
private void Form2_Deactivate(object sender, EventArgs e)
{
Application.Exit();
}
private void megoldas_Click(object sender, EventArgs e)
{
label1.Text = "";
back(1);
if (db == 0) megoldas.Items.Add("Nincs megoldas!");
string c = Convert.ToString(db);
megoldas.Items.Add(c+" db megoldas van");
megoldas.Enabled = false;
}
private void label1_Click(object sender, EventArgs e)
{
label1.Text = "";
back(1);
if (db == 0) megoldas.Items.Add("Nincs megoldas!");
string c = Convert.ToString(db);
megoldas.Items.Add(c + " db megoldas van");
megoldas.Enabled = false;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
Source: http://msdn.microsoft.com/en-us/library/yws82c40%28v=vs.110%29.aspx
private void DrawImageRect(PaintEventArgs e)
{
// Create image.
Image newImage = Image.FromFile("SampImag.jpg");
// Create rectangle for displaying image.
Rectangle destRect = new Rectangle(100, 100, 450, 150);
// Draw image to screen.
e.Graphics.DrawImage(newImage, destRect);
}
If you really need to draw it yourself, use: DrawImage.
In general it's usually easier to use a PictureBox, though.