Example O1: Scale bar

The following script renders a scale bar into the viewport (with a fixed length of 4 nm, as shown in the example picture). You can copy/paste the source code into the script input field and adjust the parameters in the code as needed.

../../../_images/python_script_scale_bar_example.png
from PySide2.QtCore import *
from PySide2.QtGui import *

# Parameters:
bar_length = 40   # Simulation units (e.g. Angstroms)
bar_color = QColor(0,0,0)
label_text = "{} nm".format(bar_length/10)
label_color = QColor(255,255,255)

# This function is called by OVITO on every viewport update.
def render(args):
    if args.is_perspective:
        raise Exception("This overlay only works with non-perspective viewports.")

    # Compute length of bar in screen space
    screen_length = args.project_size((0,0,0), bar_length)

    # Define geometry of bar in screen space
    height = 0.07 * args.painter.window().height()
    margin = 0.02 * args.painter.window().height()
    rect = QRectF(margin, margin, screen_length, height)

    # Render bar rectangle
    args.painter.fillRect(rect, bar_color)

    # Render text label
    font = args.painter.font()
    font.setPixelSize(height)
    args.painter.setFont(font)
    args.painter.setPen(QPen(label_color))
    args.painter.drawText(rect, Qt.AlignCenter, label_text)

© 2020 OVITO GmbH.