Message 1 of 8
C# - Hatching a block reference.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
Hello,
I want to hatch a block reference shown below. I am able to hatch it in solid, but the hatching is displaced by x distance and y height. I feel it's something related to z axis but I am not able to figure it out.
Can you please suggest something.
Special shout out to @Alexander.Rivilis
Code is below:
public void ColorBlock(ObjectId thePANBLKBlockTableRecord, short colorIndex)
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// Check to make sure a valid SelectedObject object was returned
if (thePANBLKBlockTableRecord != null)
{
try
{
Entity ent = (Entity)tr.GetObject(thePANBLKBlockTableRecord, OpenMode.ForWrite);
// Should always be a block reference, but let's make sure
BlockReference br = ent as BlockReference;
if (br != null)
{
// Change the color of the block itself
br.UpgradeOpen();
br.ColorIndex = colorIndex;
// Change every entity to be of color ByBlock
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(
br.BlockTableRecord, OpenMode.ForWrite);
#region Square
Point2d pt = new Point2d(br.Position.X, br.Position.Y);
Autodesk.AutoCAD.DatabaseServices.Polyline plBox =
new Autodesk.AutoCAD.DatabaseServices.Polyline(4);
plBox.Normal = Vector3d.ZAxis;
plBox.AddVertexAt(0, pt, 0.0, 0, 0);
plBox.AddVertexAt(1, new Point2d(pt.X + 4, pt.Y), 0.0, 0, 0);
plBox.AddVertexAt(2, new Point2d(pt.X + 4, pt.Y + 4), 0.0, 0, 0);
plBox.AddVertexAt(3, new Point2d(pt.X, pt.Y + 4), 0.0, 0, 0);
plBox.Closed = true;
ObjectId pLineId;
pLineId = btr.AppendEntity(plBox);
tr.AddNewlyCreatedDBObject(plBox, true);
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(pLineId);
Hatch oHatch = new Hatch();
Vector3d normal = new Vector3d(0,0, 1);
oHatch.Normal = normal;
oHatch.Elevation = 0.0;
oHatch.PatternScale = 2;
oHatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
oHatch.ColorIndex = colorIndex;
btr.AppendEntity(oHatch);
tr.AddNewlyCreatedDBObject(oHatch, true);
oHatch.Associative = true;
oHatch.AppendLoop((int)HatchLoopTypes.Default, acObjIdColl);
oHatch.EvaluateHatch(true);
#endregion
#endregion
#region Color the boundary red
// Iterate through the BlockTableRecord contents
foreach (ObjectId id in btr)
{
// Open the entity
Entity ent2 = (Entity)tr.GetObject(id, OpenMode.ForWrite);
// Change each entity's color to ByBlock
ent2.Color = Color.FromColorIndex(ColorMethod.ByBlock, colorIndex);
}
#endregion
}
}
catch (Autodesk.AutoCAD.Runtime.Exception e)
{
ed.WriteMessage(e.ToString());
}
}
tr.Commit();
}
}
