CAD二次开发之 会旋转的彩色风车
/// <summary>
/// 会旋转的风车
/// </summary>
[CommandMethod("RotatingFan")]
public void RotatingFan()
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
ObjectId id;
BlockTableRecord btr = new BlockTableRecord();
double radius = 500;
double rad2deg = Math.PI / 180;
Point3d center = Point3d.Origin;
using (var lockDoc = doc.LockDocument())
{
using (var tr = db.TransactionManager.StartTransaction())
{
Circle circle = new Circle(center, Vector3d.ZAxis, radius);
Line line1 = new Line(new Point3d(center.X - radius, center.Y, 0), new Point3d(center.X + radius, center.Y, 0));
Line line2 = new Line(new Point3d(center.X, center.Y - radius, 0), new Point3d(center.X, center.Y + radius, 0));
Arc arc1 = new Arc(new Point3d(center.X + radius / 2, center.Y, 0), Vector3d.ZAxis, radius / 2, 0 * rad2deg, 180 * rad2deg);
Arc arc2 = new Arc(new Point3d(center.X - radius / 2, center.Y, 0), Vector3d.ZAxis, radius / 2, 180 * rad2deg, 360 * rad2deg);
Arc arc3 = new Arc(new Point3d(center.X, center.Y + radius / 2, 0), Vector3d.ZAxis, radius / 2, 90 * rad2deg, 270 * rad2deg);
Arc arc4 = new Arc(new Point3d(center.X, center.Y - radius / 2, 0), Vector3d.ZAxis, radius / 2, 270 * rad2deg, 450 * rad2deg);
arc1.ColorIndex = 1;
arc2.ColorIndex = 2;
arc3.ColorIndex = 3;
arc4.ColorIndex = 4;
btr.AppendEntity(circle);
btr.AppendEntity(line1);
btr.AppendEntity(line2);
btr.AppendEntity(arc1);
btr.AppendEntity(arc2);
btr.AppendEntity(arc3);
btr.AppendEntity(arc4);
var bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
id = bt.Add(btr);
tr.AddNewlyCreatedDBObject(btr, true);
var ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
var br = new BlockReference(new Point3d(100, 100, 0), id);
id = ms.AppendEntity(br);
tr.AddNewlyCreatedDBObject(br, true);
tr.Commit();
using (ViewTableRecord view = new ViewTableRecord())
{
db.UpdateExt(true);
Point3d max = db.Extmax;
Point3d min = db.Extmin;
Point2d max_2d = new Point2d(max.X, max.Y);
Point2d min_2d = new Point2d(min.X, min.Y);
view.CenterPoint = new Point2d(min_2d.X + (max_2d.X - min_2d.X) / 2, min_2d.Y + (max_2d.Y - min_2d.Y) / 2);
view.Height = (max_2d.Y - min_2d.Y);
view.Width = (max_2d.X - min_2d.X);
doc.Editor.SetCurrentView(view);
db.UpdateExt(true);
}
}
}
//采用50Hz更新速率,每帧20ms
int fps = 50;
int frame = 1000 / fps;
//基准速度0.01度每帧,也就是5度每秒
double baseSpeed = 0.01;
//可以通过调整速度系数,来调整旋转速率
double speedFactor = 1;
bool rotated = false;
while (true)
{
var seconds = DateTime.Now.Millisecond;
if (seconds % 20 == 0 && rotated == false)
{
using (var lockDoc = doc.LockDocument())
{
using (var tr = db.TransactionManager.StartTransaction())
{
var br = tr.GetObject(id, OpenMode.ForWrite) as BlockReference;
br.Rotation += baseSpeed* speedFactor;
br.Rotation %= 360;
tr.Commit();
}
}
doc.Editor.UpdateScreen();
rotated = true;
}
if (seconds % 20 != 0 && rotated == true)
{
rotated = false;
}
}
}