1. 程式人生 > >C#繪製三角形以及旋轉

C#繪製三角形以及旋轉

三角形類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace transform
{
    class Triangle
    {
        PointF A, B, C;

        public Triangle(PointF a,PointF b,PointF c)
        {
            A = a;
            B
= b; C = c; } /// <summary> /// 繪製三角形 /// </summary> /// <param name="g"></param> public void Draw(Graphics g) { Pen pen = new Pen(Color.Red,5); g.DrawLine(pen, A, B); g.DrawLine(pen, B
, C)
; g.DrawLine(pen, C, A); } /// <summary> /// 三角形旋轉 /// </summary> /// <param name="degrees"></param> public void Rotate(int degrees) { float angle = (float)(degrees / 360f * Math.PI); float newX = (float
)
(A.X * Math.Cos(angle) - A.Y * Math.Sin(angle)); float newY = (float)(A.X * Math.Sin(angle) + A.Y * Math.Cos(angle)); A.X = newX; A.Y = newY; newX = (float)(B.X * Math.Cos(angle) - B.Y * Math.Sin(angle)); newY = (float)(B.X * Math.Sin(angle) + B.Y * Math.Cos(angle)); B.X = newX; B.Y = newY; newX = (float)(C.X * Math.Cos(angle) - C.Y * Math.Sin(angle)); newY = (float)(C.X * Math.Sin(angle) + C.Y * Math.Cos(angle)); C.X = newX; C.Y = newY; } } }

C# form:

using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace transform
{
    public partial class Form1 : Form
    {
        Triangle t;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            PointF A = new PointF(0, -200);
            PointF B = new PointF(200, 200);
            PointF C = new PointF(-200, 200);

            t = new Triangle(A, B, C);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.TranslateTransform(300, 300);
            t.Draw(e.Graphics);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            t.Rotate(1);
            this.Invalidate();
        }
    }
}

使用C#自帶的視窗程式
1.建立一個三角形類 使用了C#繪製方法
2.form中新增繪製方法,新增一個定時器
3.定時器中需要設定視窗無效 可以實時進行重繪 顯示旋轉
4.開啟雙快取避免顯示一閃一閃