Hi @mayur_kapadnis ,
try it with the following code
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
[assembly: CommandClass(typeof(TextureMappingExample))]
public class TextureMappingExample
{
[CommandMethod("MapTexture")]
public void MapTexture()
{
// Get the active document and database
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// Select a surface
PromptEntityOptions peo = new PromptEntityOptions("\nSelect a surface: ");
peo.SetRejectMessage("\nOnly surfaces are allowed.");
peo.AddAllowedClass(typeof(Surface), true);
PromptEntityResult per = doc.Editor.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
// Open the surface for write
ObjectId surfaceId = per.ObjectId;
Surface surface = tr.GetObject(surfaceId, OpenMode.ForWrite) as Surface;
if (surface == null)
{
doc.Editor.WriteMessage("\nSelected entity is not a surface.");
return;
}
// Add a material with texture
ObjectId materialId = AddMaterialWithTexture(db, tr, "MyTextureMaterial", "path_to_your_image.jpg");
// Apply the material to the surface
if (!materialId.IsNull)
{
surface.MaterialId = materialId;
surface.MaterialMapper.MaterialTransform = Matrix3d.Identity;
}
tr.Commit();
}
}
private ObjectId AddMaterialWithTexture(Database db, Transaction tr, string materialName, string imagePath)
{
// Get the material dictionary
ObjectId materialDictId = db.MaterialDictionaryId;
DBDictionary materialDict = tr.GetObject(materialDictId, OpenMode.ForWrite) as DBDictionary;
// Check if material already exists
if (materialDict.Contains(materialName))
{
return materialDict.GetAt(materialName);
}
// Create a new material
Material material = new Material
{
Name = materialName,
DiffuseMap = new MaterialMap
{
Source = FileMaterialSource.File,
Filename = imagePath
}
};
// Add the material to the dictionary
ObjectId materialId = materialDict.SetAt(materialName, material);
tr.AddNewlyCreatedDBObject(material, true);
return materialId;
}
}
Furthermore, there is an extensive code from Pavliukas, which was made available in 2007. Many thanks for that.
https://forum.dwg.ru/showthread.php?t=15000&highlight=%EC%E0%F2%E5%F0%E8%E0%EB&pp=10000