**
视口不能通过Entity.TransformBy来进行旋转操作,通过修改Viewport的属性TwistAngle、ViewCenter,同时旋转NonRectClipEntityId实体,达到旋转视口的目的。
**
[CommandMethod("RotateVP")]
public void RotateViewPort()
{
ObjectId viewportId = ObjectId.Null;
while (true)
{
PromptSelectionOptions pso = new PromptSelectionOptions
{
MessageForAdding = "n请选择视口:",
SingleOnly = true
};
PromptSelectionResult psr = MCommands.CurrentEditor.GetSelection(pso);
if (psr.Status != PromptStatus.OK) return;
foreach (var id in psr.Value.GetObjectIds())
{
if (id.ObjectClass.DxfName.ToUpper().Equals("VIEWPORT"))
{
viewportId = id;
break;
}
}
if (viewportId.IsValid) break;
}
double rotateAngle = Math.PI * 0.25;//设置旋转角度45°
using (Transaction tr = MCommands.CurrentDoc.TransactionManager.StartTransaction())
{
Viewport vp = tr.GetObject(viewportId, OpenMode.ForWrite) as Viewport;
if (vp.NonRectClipEntityId.IsNull)
{
//说明视口是矩形视口
ObjectId plId = ObjectId.Null;
using (BlockTableRecord btr = tr.GetObject(vp.BlockId, OpenMode.ForWrite) as BlockTableRecord)
{
//生成视口裁剪区域
Point2d ptLeftBottom = new Point2d(vp.CenterPoint.X - vp.Width * 0.5, vp.CenterPoint.Y -
vp.Height * 0.5);
Point2d ptRightBottom = new Point2d(vp.CenterPoint.X + vp.Width * 0.5, vp.CenterPoint.Y -
vp.Height * 0.5);
Point2d ptRightTop = new Point2d(vp.CenterPoint.X + vp.Width * 0.5, vp.CenterPoint.Y +
vp.Height * 0.5);
Point2d ptLeftTop = new Point2d(vp.CenterPoint.X - vp.Width * 0.5, vp.CenterPoint.Y +
vp.Height * 0.5);
Polyline pl = new Polyline();
pl.AddVertexAt(0, ptLeftBottom, 0, 0, 0);
pl.AddVertexAt(1, ptRightBottom, 0, 0, 0);
pl.AddVertexAt(2, ptRightTop, 0, 0, 0);
pl.AddVertexAt(3, ptLeftTop, 0, 0, 0);
pl.Closed = true;
plId= btr.AppendEntity(pl);
tr.AddNewlyCreatedDBObject(pl, true);
}
vp.NonRectClipEntityId = plId;
vp.NonRectClipOn = true;
}
vp.TwistAngle += rotateAngle;
vp.ViewCenter = vp.ViewCenter.RotateBy(rotateAngle, Point2d.Origin);
Entity ent = tr.GetObject(vp.NonRectClipEntityId, OpenMode.ForWrite) as Entity;
ent.TransformBy(Matrix3d.Rotation(rotateAngle, Vector3d.ZAxis, vp.CenterPoint));
tr.Commit();
}
}



