В качестве фона фона я использовал C# довольно давно, но не в этом случае. Мой наставник как маленький вызов попросил меня «Повернуть прямоугольник». Я достиг этого, используя Graphics и Matrix.RotateAt метод. Все работало отлично с помощью одного прямоугольника. Однако я хотел расширить его и создать класс под названием «Квадрат», который имеет положение и размер и функцию для его вращения. В настоящее время я немного изменил эту идею, и теперь у меня проблема, когда площадь, похоже, сильно вращается.C# Графика Прямоугольник, вращающийся настойчиво
Я создал очень короткое видео и загрузить его на YouTube:
https://www.youtube.com/watch?v=KwQjDKfExtg&feature=youtu.be
Здесь вы можете видеть, что я пытался закомментируйте весь ненужный код.
//Import this namespace which it auto-generated for my Square class.
using CSharpIntro.Classes.Shapes_Rotation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace CSharpIntro
{
public partial class Form1 : Form
{
//int rotateDegrees = 0;
int numOfSquares = 1;
List<Square> squares = new List<Square>();
//Instantiate a new Matrix class.
Matrix myMatrix = new Matrix();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < numOfSquares; i++)
{
Square square = new Square();
//Random rand = new Random();
//square.boxX = rand.Next(0, ActiveForm.Size.Width);
//square.boxY = rand.Next(0, ActiveForm.Size.Height);
squares.Add(square);
//MessageBox.Show("A square has been created");
}
}
//private void DrawLineOnScreen()
//{
// Random rand = new Random();
// Color randomColour = new Color();
// randomColour = Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255));
// Pen myPen = new Pen(randomColour);
// Graphics graphics = CreateGraphics();
// graphics.DrawLine(myPen, rand.Next(0, ActiveForm.Size.Width), rand.Next(0, ActiveForm.Size.Height), rand.Next(0, ActiveForm.Size.Width), rand.Next(0, ActiveForm.Size.Height));
// myPen.Dispose();
// graphics.Dispose();
//}
private void RectRotateTimer_Tick(object sender, EventArgs e)
{
// Pen myPen = new Pen(Color.Red, 5);
// Graphics graphics = CreateGraphics();
// graphics.Clear(Color.White);
// int boxX = 100;
// int boxY = 100;
// int boxWidth = 100;
// int boxHeight = 100;
// //Get the rotation point
// //get the X position of the rectangle and add half of thw width to get the X.
// //get the Y position of the rectangle and add half of the height to get the Y.
// PointF rotatePoint = new PointF((boxX + (boxWidth/2)), (boxY + (boxHeight/2)));
// myMatrix.RotateAt(rotateDegrees, rotatePoint, MatrixOrder.Append);
// graphics.Transform = myMatrix;
// graphics.DrawRectangle(myPen, boxX, boxY, boxWidth, boxHeight);
// //Increment the rotation by 1 each tick.
// rotateDegrees += 1;
// //If rotateDegress is greater than 360, set it to 0.
// //360 is a full spin.
// if (rotateDegrees > 360)
// rotateDegrees = 0;
// //Debug information.
// //Console.WriteLine(rotateDegrees);
// //Dispose of the graphics and pen so we dont cause a memory leak.
// myPen.Dispose();
// graphics.Dispose();
}
private void RotateAllSquares_Tick(object sender, EventArgs e)
{
DrawAllRectangles();
}
public void DrawAllRectangles()
{
for (int i = 0; i < squares.Count; i++)
{
Pen myPen = new Pen(Color.Red, 3);
Graphics graphics = CreateGraphics();
graphics.Clear(Color.White);
PointF rotatePoint = new PointF((squares[i].boxX + (squares[i].boxWidth/2)), (squares[i].boxY + (squares[i].boxHeight/2)));
myMatrix.RotateAt(squares[i].rotateDegrees, rotatePoint, MatrixOrder.Append);
graphics.Transform = myMatrix;
graphics.DrawRectangle(myPen, squares[i].boxX, squares[i].boxY, squares[i].boxWidth, squares[i].boxHeight);
squares[i].rotateDegrees ++;
myPen.Dispose();
graphics.Dispose();
Console.WriteLine(string.Format("A square has been rotated at {0}, {1}", squares[i].boxX, squares[i].boxY));
Console.WriteLine(squares[i].rotateDegrees);
}
}
}
}
И вот простой квадратный класс, который, как вы можете видеть, также в основном прокомментирован сейчас.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace CSharpIntro.Classes.Shapes_Rotation
{
public class Square
{
//Create the variables with some basic numbers
//Just in case they dont get set for some reason.
public int boxX = 100;
public int boxY = 100;
public int boxWidth = 100;
public int boxHeight = 100;
public int rotateDegrees = 0;
//Create a new Matrix class
Matrix myMatrix = new Matrix();
public void IncrementRotationDegrees()
{
rotateDegrees += 1;
if (rotateDegrees > 360)
rotateDegrees = 1;
}
//public void RotateSquare()
//{
// Pen myPen = new Pen(Color.Red, 5);
// //Instantiate a new Form1 just so I can access CreateGraphics().
// Form1 form = new Form1();
// Graphics graphics = form.CreateGraphics();
// graphics.Clear(Color.White);
// //Get the rotation point
// //get the X position of the rectangle and add half of thw width to get the X.
// //get the Y position of the rectangle and add half of the height to get the Y.
// PointF rotatePoint = new PointF((boxX + (boxWidth/2)), (boxY + (boxHeight/2)));
// myMatrix.RotateAt(rotateDegrees, rotatePoint, MatrixOrder.Append);
// graphics.Transform = myMatrix;
// graphics.DrawRectangle(myPen, boxX, boxY, boxWidth, boxHeight);
// //Increment the rotation by 1 each tick.
// rotateDegrees += 1;
// //If rotateDegress is greater than 360, set it to 0.
// //360 is a full spin.
// if (rotateDegrees > 360)
// rotateDegrees = 0;
// //Debug information.
// //Console.WriteLine(rotateDegrees);
// //Dispose of the graphics and pen so we dont cause a memory leak.
// myPen.Dispose();
// graphics.Dispose();
//}
}
}
Поскольку большая часть этого кода была закомментирована, я до сих пор просто не знаю, что могло бы заставить его сильно вращаться.
Спасибо.
Каковы свойства RotateAllSquares, которые вы размещаете на своей форме? –
Включено, конечно, с интервалом 10 мс. Это означает, что для полного вращения требуется 3,6 секунды. Я получу видео об этом, работая нормально со старым методом, если смогу. – GamingAnonymous
Похоже, вы продолжаете добавлять угол поворота, но никогда не сбрасываете матрицу. Вращение поэтому растет и растет. Если вы хотите, чтобы он был равномерным, не меняйте его, скажем, 1, или просто сбросьте матрицу ... – TaW