Autodesk Community Tips- ADNオープン
Autodesk Community Tipsではちょっとしたコツ、やり方、ショートカット、アドバイスやヒントを共有しています。

AutoCAD .net APIでエンティティマウスドラッグ操作(移動・回転 等)でマウス操作に追随してプレビューイメージを表示する方法

Question

AutoCAD .net APIで、エンティティマウスドラッグ操作(移動・回転 等)でマウス操作に追随してプレビューイメージを表示するにはどうしたらよいでしょうか。

Answer

AutoCAD .net APIのEntityJigの仕組みが利用可能です。

 

EntityJigを継承したクラスを作成し、Sampler()メソッドをとUpdate()メソッドをオーバライドして、入力に応じた処理を実装します。

 

以下は、マウスに追随してプレビューを表示しながら選択したエンティティを回転させるサンプルコードとなります。 

[CommandMethod("MyRotateEnt")]
public static void MyRotateEnt()
{
	Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
	Database db = HostApplicationServices.WorkingDatabase;
	PromptEntityResult per = ed.GetEntity("\nPick an entity:");
	if (per.Status != PromptStatus.OK)
        {
		return;
	}

	PromptPointResult pr = ed.GetPoint("\nBase Point: ");
	if(pr.Status != PromptStatus.OK)
	{
		return;
        }

	try
	{
		using (Transaction tx = db.TransactionManager.StartTransaction())
		{
			Entity ent = tx.GetObject(per.ObjectId, OpenMode.ForWrite) as Entity;
			if (ent != null)
			{
				RotateJigger jigger = new RotateJigger(ent, pr.Value, ed.CurrentUserCoordinateSystem);
				if (jigger.Run() == PromptStatus.OK)
				{
					tx.Commit();							
				}
			}
		}
	}
	catch (System.Exception ex)
	{
		ed.WriteMessage(ex.ToString());
	}
}



public class RotateJigger : EntityJig
{
	private double mRt = 0.0;
	private Point3d mBp = new Point3d();
	private double mLastAngle = 0.0;
	private Matrix3d mUcs;
	public RotateJigger(Entity ent, Point3d bp, Matrix3d ucs) : base(ent)
	{
		mBp = bp;
		mUcs = ucs;
	}

	protected override bool Update()
	{
		Point3d basePt = new Point3d(mBp.X, mBp.Y, mBp.Z);
		Matrix3d mat = Matrix3d.Rotation(mRt - mLastAngle
			, Vector3d.ZAxis.TransformBy(mUcs)
			, basePt.TransformBy(mUcs));
		this.Entity.TransformBy(mat);
		mLastAngle = mRt;
		return true;
	}

	protected override SamplerStatus Sampler(JigPrompts prompts)
	{
		PromptDoubleResult pr = prompts.AcquireAngle(
			new JigPromptAngleOptions("\nRotation angle:")
		{
			BasePoint = mBp,
			UseBasePoint = true
		});

		if (pr.Status == PromptStatus.Cancel) 
			return SamplerStatus.Cancel;

		if (pr.Value.Equals(mRt))
		{
			return SamplerStatus.NoChange;
		}

		mRt = pr.Value;
		return SamplerStatus.OK;
	}

	public PromptStatus Run()
	{
		Document doc = Application.DocumentManager.MdiActiveDocument;
		if (doc == null)
			return PromptStatus.Error;

		return doc.Editor.Drag(this).Status;
	}
}