我正在嘗試創建程序,其中將在畫布上繪製魚類列表。 (下一步將根據一些計算改變魚類的位置) 每個魚都由位圖表示(png文件7x12像素與魚的圖片)。
C#旋轉(轉換)問題
我創建了FormBox,它是PictureBox,它是我的繪圖畫布。它有大小640x480像素。
在下面的代碼是我使用的簡化代碼(我切斷了所有不需要的東西)。我的問題是轉矩矩陣,此時只有旋轉。
問題是類魚在方法來繪製()這裏我試圖做一個改造的探討,此刻我設置了旋轉的每條魚30度,但後來每條魚都會有不同的起始旋轉角度。我想對魚的旋轉角度繞其中心旋轉的位置進行轉換。所以在這種情況下,所有的魚都應該在一條線上,並且每條魚的旋轉角度(這裏是30度)都要旋轉。
但他們被放置在diagonale,所以轉換搞砸了。 我該如何解決這個問題? 我可能無法正確使用轉換。
命名空間使用類
using System.Drawing;//Graphics, Point
using System.Drawing.Drawing2D;//Matrix
魚
class Fish {
public Point position;
public int rotation;
public Graphics g;
public Image fishImage;
private Rectangle rect;
private Matrix matrix;
public Fish(ref Graphics g, int x, int y, int rotation,Image img){
this.g = g;
position = new Point(x,y);
this.rotation = rotation;
this.fishImage = img;
this.rect = new Rectangle(position.X,position.Y, fishImage.Width, fishImage.Height);
}
public void Draw() {
matrix = new Matrix();
matrix.Rotate((float)rotation, Matrix.Append); //if i comment this it
//will be drawn in one line
//according to the initial values for position
//if i let the rotation here it will be on diagonale
//i want it on one line but rotated
g.Transform = matrix;
rect = new Rectangle(position.X, position.Y, fishImage.Width, fishImage.Height);
g.DrawImage(fishImage, rect);
}
}//end Fish class
表格
public partial class Form1 : Form
{
private Bitmap canvasBitmap; //bitmap for drawing
private Graphics g;
Image fishImage;
private List<Fish> fishes = new List<Fish>();
public Form1() {
InitializeComponent();
//png image 7x12 pixels
fishImage = FishGenetic.Properties.Resources.fishImage;
//on Form there is placed PictureBox called canvas
//so canvas is PictureBox 640x480 px
canvasBitmap = new Bitmap(canvas.Width, canvas.Height);
canvas.Image = canvasBitmap;
//prepare graphics
g = Graphics.FromImage(canvasBitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
InitFishes();
DrawFishes();
canvas.Invalidate(); //invalidate the canvas
}//end Form1 constructor
private void InitFishes() {
Fish fish1 = new Fish(ref g, 10, 10, 30, fishImage);
Fish fish2 = new Fish(ref g, 20, 10, 30, fishImage);
Fish fish3 = new Fish(ref g, 30, 10, 30, fishImage);
Fish fish4 = new Fish(ref g, 40, 10, 30, fishImage);
Fish fish5 = new Fish(ref g, 50, 10, 30, fishImage);
fishes.Add(fish1);
fishes.Add(fish2);
fishes.Add(fish3);
fishes.Add(fish4);
fishes.Add(fish5);
}
private void DrawFishes() {
foreach(Fish fish in fishes) {
fish.Draw();
}
}
}//end Form1 class
Main類
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
@x ...但我應該如何使用Paint事件?其重寫我的事物OnPaint方法,但在哪裏?我的意思是什麼對象?這與我用於在窗體上創建畫布(PictureBox)的Grafic g有什麼關係? – user1097772