案例:ex_activeviewport.py
import Rhino
import scriptcontext
import System.Windows.Forms.DialogResult
import System.Drawing.Image
def AddBackgroundBitmap():
# Allow the user to select a bitmap file
fd = Rhino.UI.OpenFileDialog()
fd.Filter = "Image Files (*.bmp;*.png;*.jpg)|*.bmp;*.png;*.jpg"
if fd.ShowDialog()!=System.Windows.Forms.DialogResult.OK:
return Rhino.Commands.Result.Cancel
# Verify the file that was selected
image = None
try:
image = System.Drawing.Image.FromFile(fd.FileName)
except:
return Rhino.Commands.Result.Failure
# Allow the user to pick the bitmap origin
gp = Rhino.Input.Custom.GetPoint()
gp.SetCommandPrompt("Bitmap Origin")
gp.ConstrainToConstructionPlane(True)
gp.Get()
if gp.CommandResult()!=Rhino.Commands.Result.Success:
return gp.CommandResult()
# Get the view that the point was picked in.
# This will be the view that the bitmap appears in.
view = gp.View()
if view is None:
view = scriptcontext.doc.Views.ActiveView
if view is None: return Rhino.Commands.Result.Failure
# Allow the user to specify the bitmap with in model units
gn = Rhino.Input.Custom.GetNumber()
gn.SetCommandPrompt("Bitmap width")
gn.SetLowerLimit(1.0, False)
gn.Get()
if gn.CommandResult()!=Rhino.Commands.Result.Success:
return gn.CommandResult()
# Cook up some scale factors
w = gn.Number()
h = w * (image.Width / image.Height)
plane = view.ActiveViewport.ConstructionPlane()
plane.Origin = gp.Point()
view.ActiveViewport.SetTraceImage(fd.FileName, plane, w, h, False, False)
view.Redraw()
return Rhino.Commands.Result.Success
if __name__=="__main__":
AddBackgroundBitmap()
功能
解析:ex_addbackgroundbitmap.py
这是一段使用Rhino.Python脚本编写的代码,用于在Rhino软件中添加背景位图。代码的具体功能如下:
- 弹出对话框,允许用户选择一个位图文件(bmp、png或jpg格式)作为背景图像。
- 验证所选文件是否有效,如果无效则返回失败。
- 允许用户选择位图在Rhino文档中的位置和大小,并将其添加到当前视图中作为背景图像。
下面是代码的具体解释:
- 首先导入Rhino和System.Windows.Forms命名空间以及System.Drawing.Image类。
- 定义AddBackgroundBitmap()函数,该函数用于添加背景位图。
- 使用Rhino.UI.OpenFileDialog()方法弹出文件对话框,允许用户选择位图文件,并设置过滤器以限制文件类型。
- 验证所选文件是否有效,如果无效则返回失败。
- 使用Rhino.Input.Custom.GetPoint()方法允许用户在Rhino文档中选择位图的位置,并获取选择点所在的视图。
- 使用Rhino.Input.Custom.GetNumber()方法允许用户选择位图的大小,并计算位图的宽高比。
- 获取当前视图的构造平面,并将其设置为选择点的位置。
- 使用view.ActiveViewport.SetTraceImage()方法将位图添加到当前视图中作为背景图像,并指定位图的位置、大小和是否重复。
- 最后使用view.Redraw()方法刷新当前视图以显示新添加的背景图像。
在代码中,如果用户取消选择文件或操作失败,则会返回Rhino.Commands.Result.Cancel或Rhino.Commands.Result.Failure。如果操作成功,则返回Rhino.Commands.Result.Success。