本帖最后由 hubeiwdlue 于 2025-4-2 17:10 编辑
关于创建块,最常用的方法是command方法,简单,实用:
 - (command "_.block" blkname "non" pt ss "")
- (command "_.insert" blkname "x" 1 "y" 1 "z" 1 "r" 0 "non" inspt);插入块
另外一种常用的方法是entmake方法创建块:
 - (defun MAKE-BLOCK (ss pt blkName / i num)
- (if (/= (getvar "HANDLES") 1)
- (command "HANDLES" "ON")
- ) ;_ 结束if
- (entmake (list '(0 . "BLOCK")
- (cons 2 blkName)
- '(70 . 0)
- (cons 10 PT)
- ) ;_ 结束list
- ) ;_ 结束entmake
- (setq i -1)
- (repeat (sslength ss)
- (entmake (cdr (entget (ssname ss (setq i (1+ i))))))
- ) ; repeat
- (setq num (entmake '((0 . "ENDBLK"))))
- (entmake
- (list '(0 . "INSERT")
- (cons 2 num)
- (cons 10 pt)
- ) ;_ 结束list
- ) ;_ 结束entmake
- (command "erase" ss "")
- (entlast)
- )
- (setq ss (ssget))
- (setq pt (getpoint))
- (setq name (getstring))
- (MAKE-BLOCK ss pt name)
vla的方法创建块,论坛上没找到完整的例子,问了一下ai,整理了一个vla创建块的代码,如下:
 - (defun CreateBlockByVLA (ss basePt blkName / acadDoc blkCol blkInsert blockObj UniqueBlockName modelSpace obj)
- (vl-load-com)
- ;; 生成唯一块名
- (defun UniqueBlockName (name / blockTable count newname)
- (setq blockTable (vla-get-Blocks (vla-get-ActiveDocument (vlax-get-acad-object))))
- (setq count 1
- newname name)
- (while (not (vl-catch-all-error-p
- (vl-catch-all-apply 'vla-Item (list blockTable newname))))
- (setq newname (strcat name "$" (itoa count)))
- (setq count (1+ count))
- )
- newname
- )
- (setq acadDoc (vla-get-ActiveDocument (vlax-get-acad-object)))
- (setq blkCol (vla-get-Blocks acadDoc))
- (setq modelSpace (vla-get-ModelSpace acadDoc))
- ;; 处理重命名,确保块名唯一
- (setq blkName (UniqueBlockName blkName))
- ;; 创建新块
- (setq blockObj (vlax-invoke blkCol 'Add basePt blkName))
- ;; 复制对象到块定义
- (and ss (= 'pickset (type ss))
- (progn
- (vl-cmdf "SELECT" ss "")
- (ssget "P")
- )
- )
- (vlax-for obj (vla-get-ActiveSelectionSet acadDoc)
- (vla-CopyObjects acadDoc
- (vlax-make-variant
- (vlax-safearray-fill
- (vlax-make-safearray vlax-vbObject '(0 . 0))
- (list obj)
- )
- )
- blockObj
- )
- (vla-Delete obj)
- )
- ;; 在模型空间插入块
- (setq blkInsert (vla-InsertBlock modelSpace
- (vlax-3d-point basePt) ; 插入点(与块基点相同)
- blkName ; 块名
- 1.0 1.0 1.0 ; X/Y/Z比例
- 0.0 ; 旋转角度
- ))
- blkInsert
- )
- (defun c:tt ()
- (setq ss (ssget))
- (if ss
- (progn
- (setq basePt (getpoint "\n选择块的基点: "))
- (setq blkName (getstring "\n输入块名: "))
- (CreateBlockByVLA ss basePt blkName)
- )
- (princ "\n未选择对象,操作取消。")
- )
- (princ)
- )
|